<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>Java泛型与集合类 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="Java泛型与集合类"><meta property="og:title" content="Java泛型与集合类" />
<meta property="og:description" content="Java泛型与集合类" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-01-23T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-01-23T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="Java泛型与集合类"/>
<meta name="twitter:description" content="Java泛型与集合类"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" /><link rel="prev" href="https://acking-you.github.io/posts/c&#43;&#43;%E7%9A%84%E6%A8%A1%E6%9D%BF%E5%86%99println/" /><link rel="next" href="https://acking-you.github.io/posts/java%E5%BC%82%E5%B8%B8/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Java泛型与集合类",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB\/"
        },"genre": "posts","keywords": "Java泛型与集合类","wordcount":  17598 ,
        "url": "https:\/\/acking-you.github.io\/posts\/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB\/","datePublished": "2022-01-23T00:00:00+00:00","dateModified": "2022-01-23T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "Java泛型与集合类"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center, https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center 1.5x, https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"
        title="Java泛型与集合类" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">Java泛型与集合类</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/javase%E7%AC%94%E8%AE%B0/"><i class="far fa-folder fa-fw"></i>JavaSE笔记</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-01-23">2022-01-23</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 17598 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 36 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#走进泛型">走进泛型</a></li>
    <li><a href="#泛型的使用">泛型的使用</a>
      <ul>
        <li><a href="#泛型类">泛型类</a></li>
        <li><a href="#类的泛型方法">类的泛型方法</a></li>
        <li><a href="#自定义泛型方法">自定义泛型方法</a></li>
        <li><a href="#泛型引用">泛型引用</a></li>
        <li><a href="#泛型的界限">泛型的界限</a></li>
        <li><a href="#钻石运算符">钻石运算符</a></li>
        <li><a href="#泛型与多态">泛型与多态</a></li>
        <li><a href="#多态类型擦除">多态类型擦除</a></li>
      </ul>
    </li>
    <li><a href="#数据结构基础">数据结构基础</a>
      <ul>
        <li><a href="#线性表">线性表</a></li>
        <li><a href="#二叉树">二叉树</a></li>
        <li><a href="#快速查找">快速查找</a></li>
      </ul>
    </li>
    <li><a href="#认识集合类">认识集合类</a>
      <ul>
        <li><a href="#数组与集合">数组与集合</a></li>
        <li><a href="#集合根接口collection">集合根接口Collection</a></li>
      </ul>
    </li>
    <li><a href="#集合类的使用">集合类的使用</a>
      <ul>
        <li><a href="#list列表">List列表</a></li>
        <li><a href="#迭代器">迭代器</a></li>
        <li><a href="#set集合">Set集合</a></li>
        <li><a href="#map映射">Map映射</a></li>
        <li><a href="#集合的嵌套">集合的嵌套</a></li>
        <li><a href="#流stream和optional的使用">流Stream和Optional的使用</a></li>
        <li><a href="#arrays和collections的使用">Arrays和Collections的使用</a></li>
      </ul>
    </li>
    <li><a href="#集合类编程实战">集合类编程实战</a>
      <ul>
        <li><a href="#反转链表">反转链表</a></li>
        <li><a href="#重建二叉树">重建二叉树</a></li>
        <li><a href="#实现计算器">实现计算器</a></li>
        <li><a href="#字符串匹配kmp算法">字符串匹配（KMP算法）</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h1 id="java泛型与集合类">Java泛型与集合类</h1>
<p><a href="https://www.bilibili.com/video/BV1Gv411T7pi?p=50" target="_blank" rel="noopener noreffer">配套视频</a></p>
<p>在前面我们学习了最重要的类和对象，了解了面向对象编程的思想，注意，非常重要，面向对象是必须要深入理解和掌握的内容，不能草草结束。在本章节，我们会继续深入了解，从我们的泛型开始，再到我们的数据结构，最后再开始我们的集合类学习。</p>
<h2 id="走进泛型">走进泛型</h2>
<p>为了统计学生成绩，要求设计一个Score对象，包括课程名称、课程号、课程成绩，但是成绩分为两种，一种是以<code>优秀、良好、合格</code> 来作为结果，还有一种就是 <code>60.0、75.5、92.5</code> 这样的数字分数，那么现在该如何去设计这样的一个Score类呢？现在的问题就是，成绩可能是<code>String</code>类型，也可能是<code>Integer</code>类型，如何才能很好的去存可能出现的两种类型呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Score</span> <span class="o">{</span>
    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
    <span class="n">Object</span> <span class="n">score</span><span class="o">;</span>  <span class="c1">//因为Object是所有类型的父类，因此既可以存放Integer也能存放String
</span><span class="c1"></span>
  	<span class="kd">public</span> <span class="nf">Score</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">id</span><span class="o">,</span> <span class="n">Object</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">id</span> <span class="o">=</span> <span class="n">id</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>以上的方法虽然很好地解决了多种类型存储问题，但是Object类型在编译阶段并不具有良好的类型判断能力，很容易出现以下的情况：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>

    <span class="n">Score</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="s">&#34;优秀&#34;</span><span class="o">);</span>  <span class="c1">//是String类型的
</span><span class="c1"></span>
    <span class="c1">//....
</span><span class="c1"></span>
    <span class="n">Integer</span> <span class="n">number</span> <span class="o">=</span> <span class="o">(</span><span class="n">Integer</span><span class="o">)</span> <span class="n">score</span><span class="o">.</span><span class="na">score</span><span class="o">;</span>  <span class="c1">//获取成绩需要进行强制类型转换，虽然并不是一开始的类型，但是编译不会报错
</span><span class="c1"></span><span class="o">}</span>

<span class="c1">//运行时出现异常！
</span><span class="c1"></span><span class="n">Exception</span> <span class="n">in</span> <span class="n">thread</span> <span class="s">&#34;main&#34;</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">ClassCastException</span><span class="o">:</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span> <span class="n">cannot</span> <span class="n">be</span> <span class="n">cast</span> <span class="n">to</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">Integer</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">main</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">14</span><span class="o">)</span>
</code></pre></div><p>使用Object类型作为引用，取值只能进行强制类型转换，显然无法在编译期确定类型是否安全，项目中代码量非常之大，进行类型比较又会导致额外的开销和增加代码量，如果不经比较就很容易出现类型转换异常，代码的健壮性有所欠缺！（此方法虽然可行，但并不是最好的方法）</p>
<p>为了解决以上问题，JDK1.5新增了泛型，它能够在编译阶段就检查类型安全，大大提升开发效率。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Score</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="o">{</span>   <span class="c1">//将Score转变为泛型类&lt;T&gt;
</span><span class="c1"></span>    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
    <span class="n">T</span> <span class="n">score</span><span class="o">;</span>  <span class="c1">//T为泛型，根据用户提供的类型自动变成对应类型
</span><span class="c1"></span>
    <span class="kd">public</span> <span class="nf">Score</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">id</span><span class="o">,</span> <span class="n">T</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>   <span class="c1">//提供的score类型即为T代表的类型
</span><span class="c1"></span>        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">id</span> <span class="o">=</span> <span class="n">id</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="c1">//直接确定Score的类型是字符串类型的成绩
</span><span class="c1"></span>    <span class="n">Score</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="s">&#34;优秀&#34;</span><span class="o">);</span>

    <span class="n">Integer</span> <span class="n">i</span> <span class="o">=</span> <span class="n">score</span><span class="o">.</span><span class="na">score</span><span class="o">;</span>  <span class="c1">//编译不通过，因为成员变量score类型被定为String！
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>泛型将数据类型的确定控制在了编译阶段，在编写代码的时候就能明确泛型的类型！如果类型不符合，将无法通过编译！</p>
<p>泛型本质上也是一个语法糖（并不是JVM所支持的语法，编译后会转成编译器支持的语法，比如之前的foreach就是），在编译后会被擦除，变回上面的Object类型调用，但是类型转换由编译器帮我们完成，而不是我们自己进行转换（安全）</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//反编译后的代码
</span><span class="c1"></span><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">Score</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="s">&#34;优秀&#34;</span><span class="o">);</span>
        <span class="n">String</span> <span class="n">i</span> <span class="o">=</span> <span class="o">(</span><span class="n">String</span><span class="o">)</span><span class="n">score</span><span class="o">.</span><span class="na">score</span><span class="o">;</span>   <span class="c1">//其实依然会变为强制类型转换，但是这是由编译器帮我们完成的
</span><span class="c1"></span>    <span class="o">}</span>
</code></pre></div><p>像这样在编译后泛型的内容消失转变为Object的情况称为<code>类型擦除</code>（重要，需要完全理解），所以泛型只是为了方便我们在编译阶段确定类型的一种语法而已，并不是JVM所支持的。</p>
<p>综上，泛型其实就是一种类型参数，用于指定类型。</p>
<h2 id="泛型的使用">泛型的使用</h2>
<h3 id="泛型类">泛型类</h3>
<p>上一节我们已经提到泛型类的定义，实际上就是普通的类多了一个类型参数，也就是在使用时需要指定具体的泛型类型。泛型的名称一般取单个大写字母，比如T代表Type，也就是<code>类型</code>的英文单词首字母，当然也可以添加数字和其他的字符。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Score</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="o">{</span>   <span class="c1">//将Score转变为泛型类&lt;T&gt;
</span><span class="c1"></span>    <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
    <span class="n">T</span> <span class="n">score</span><span class="o">;</span>  <span class="c1">//T为泛型，根据用户提供的类型自动变成对应类型
</span><span class="c1"></span>
    <span class="kd">public</span> <span class="nf">Score</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">id</span><span class="o">,</span> <span class="n">T</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>   <span class="c1">//提供的score类型即为T代表的类型
</span><span class="c1"></span>        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">id</span> <span class="o">=</span> <span class="n">id</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>在一个普通类型中定义泛型，泛型T称为<code>参数化类型</code>，在定义泛型类的引用时，需要明确指出类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"> <span class="n">Score</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="s">&#34;优秀&#34;</span><span class="o">);</span>
</code></pre></div><p>此时类中的泛型T已经被替换为String了，在我们获取此对象的泛型属性时，编译器会直接告诉我们类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Integer</span> <span class="n">i</span> <span class="o">=</span> <span class="n">score</span><span class="o">.</span><span class="na">score</span><span class="o">;</span>   <span class="c1">//编译不通过，因为成员变量score明确为String类型
</span></code></pre></div><p>注意，泛型只能用于对象属性，也就是非静态的成员变量才能使用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">static</span> <span class="n">T</span> <span class="n">score</span><span class="o">;</span>   <span class="c1">//错误，不能在静态成员上定义
</span></code></pre></div><p>由此可见，泛型是只有在创建对象后编译器才能明确泛型类型，而静态类型是类所具有的属性，不足以使得编译器完成类型推断。</p>
<p>泛型无法使用基本类型，如果需要基本类型，只能使用基本类型的包装类进行替换！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;</span><span class="kt">double</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;</span><span class="kt">double</span><span class="o">&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="n">90</span><span class="o">.</span><span class="na">5</span><span class="o">);</span>  <span class="c1">//编译不通过
</span></code></pre></div><p>那么为什么泛型无法使用基本类型呢？回想上一节提到的类型擦除，其实就很好理解了。由于JVM没有泛型概念，因此泛型最后还是会被编译器编译为Object，并采用强制类型转换的形式进行类型匹配，而我们的基本数据类型和引用类型之间无法进行类型转换，所以只能使用基本类型的包装类来处理。</p>
<h3 id="类的泛型方法">类的泛型方法</h3>
<p>泛型方法的使用也很简单，我们只需要把它当做一个未知的类型来使用即可：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="n">T</span> <span class="nf">getScore</span><span class="o">()</span> <span class="o">{</span>    <span class="c1">//若方法的返回值类型为泛型，那么编译器会自动进行推断
</span><span class="c1"></span>  <span class="k">return</span> <span class="n">score</span><span class="o">;</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kt">void</span> <span class="nf">setScore</span><span class="o">(</span><span class="n">T</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>   <span class="c1">//若方法的形式参数为泛型，那么实参只能是定义时的类型
</span><span class="c1"></span>  <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="s">&#34;优秀&#34;</span><span class="o">);</span>
<span class="n">score</span><span class="o">.</span><span class="na">setScore</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>   <span class="c1">//编译不通过，因为只接受String类型
</span></code></pre></div><p>同样地，静态方法无法直接使用类定义的泛型（注意是无法直接使用，静态方法可以使用泛型）</p>
<h3 id="自定义泛型方法">自定义泛型方法</h3>
<p>那么如果我想在静态方法中使用泛型呢？首先我们要明确之前为什么无法使用泛型，因为之前我们的泛型定义是在类上的，只有明确具体的类型才能开始使用，也就是创建对象时完成类型确定，但是静态方法不需要依附于对象，那么只能在使用时再来确定了，所以静态方法可以使用泛型，但是需要单独定义：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(</span><span class="n">E</span> <span class="n">e</span><span class="o">){</span>   <span class="c1">//在方法定义前声明泛型
</span><span class="c1"></span>  <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>同理，成员方法也能自行定义泛型，在实际使用时再进行类型确定：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="kt">void</span> <span class="nf">test</span><span class="o">(</span><span class="n">E</span> <span class="n">e</span><span class="o">){</span>
  <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>其实，无论是泛型类还是泛型方法，再使用时一定要能够进行类型推断，明确类型才行。</p>
<p>注意一定要区分类定义的泛型和方法前定义的泛型！</p>
<h3 id="泛型引用">泛型引用</h3>
<p>可以看到我们在定义一个泛型类的引用时，需要在后面指出此类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">score</span><span class="o">;</span>  <span class="c1">//声明泛型为Integer类型
</span></code></pre></div><p>如果不希望指定类型，或是希望此引用类型可以引用任意泛型的<code>Score</code>类对象，可以使用<code>?</code>通配符，来表示自动匹配任意的可用类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;?&gt;</span> <span class="n">score</span><span class="o">;</span>   <span class="c1">//score可以引用任意的Score类型对象了！
</span></code></pre></div><p>那么使用通配符之后，得到的泛型成员变量会是什么类型呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Object</span> <span class="n">o</span> <span class="o">=</span> <span class="n">score</span><span class="o">.</span><span class="na">getScore</span><span class="o">();</span>   <span class="c1">//只能变为Object
</span></code></pre></div><p>因为使用了通配符，编译器就无法进行类型推断，所以只能使用原始类型。</p>
<p>在学习了泛型的界限后，我们还会继续了解通配符的使用。</p>
<h3 id="泛型的界限">泛型的界限</h3>
<p>现在有一个新的需求，现在没有String类型的成绩了，但是成绩依然可能是整数，也可能是小数，这时我们不希望用户将泛型指定为除数字类型外的其他类型，我们就需要使用到泛型的上界定义：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Score</span><span class="o">&lt;</span><span class="n">T</span> <span class="kd">extends</span> <span class="n">Number</span><span class="o">&gt;</span> <span class="o">{</span>   <span class="c1">//设定泛型上界，必须是Number的子类
</span><span class="c1"></span>    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">T</span> <span class="n">score</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">Score</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">id</span><span class="o">,</span> <span class="n">T</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">id</span> <span class="o">=</span> <span class="n">id</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">T</span> <span class="nf">getScore</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>通过<code>extends</code>关键字进行上界限定，只有指定类型或指定类型的子类才能作为类型参数。</p>
<p>同样的，泛型通配符也支持泛型的界限：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;?</span> <span class="kd">extends</span> <span class="n">Number</span><span class="o">&gt;</span> <span class="n">score</span><span class="o">;</span>  <span class="c1">//限定为匹配Number及其子类的类型
</span></code></pre></div><p>同理，既然泛型有上限，那么也有下限：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;?</span> <span class="kd">super</span> <span class="n">Integer</span><span class="o">&gt;</span> <span class="n">score</span><span class="o">;</span>   <span class="c1">//限定为匹配Integer及其父类
</span></code></pre></div><p>通过<code>super</code>关键字进行下界限定，只有指定类型或指定类型的父类才能作为类型参数。</p>
<p>图解如下：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523263309.png"
        data-srcset="http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523263309.png, http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523263309.png 1.5x, http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523263309.png 2x"
        data-sizes="auto"
        alt="http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523263309.png"
        title="png" /></p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523264595.jpg"
        data-srcset="http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523264595.jpg, http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523264595.jpg 1.5x, http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523264595.jpg 2x"
        data-sizes="auto"
        alt="http://images4.10qianwan.com/10qianwan/20191209/b_0_201912091523264595.jpg"
        title="png" /></p>
<p>那么限定了上界后，我们再来使用这个对象的泛型成员，会变成什么类型呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;?</span> <span class="kd">extends</span> <span class="n">Number</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="n">10</span><span class="o">);</span>
<span class="n">Number</span> <span class="n">o</span> <span class="o">=</span> <span class="n">score</span><span class="o">.</span><span class="na">getScore</span><span class="o">();</span>    <span class="c1">//得到的结果为上界类型
</span></code></pre></div><p>也就是说，一旦我们指定了上界后，编译器就将范围从原始类型<code>Object</code>提升到我们指定的上界<code>Number</code>，但是依然无法明确具体类型。思考：那如果定义下限呢？</p>
<p>那么既然我们可以给泛型类限定上界，现在我们来看编译后结果呢：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//使用javap -l 进行反编译
</span><span class="c1"></span><span class="kd">public</span> <span class="kd">class</span> <span class="nc">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Score</span><span class="o">&lt;</span><span class="n">T</span> <span class="kd">extends</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">Number</span><span class="o">&gt;</span> <span class="o">{</span>
  <span class="kd">public</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Score</span><span class="o">(</span><span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span><span class="o">,</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">String</span><span class="o">,</span> <span class="n">T</span><span class="o">);</span>
    <span class="n">LineNumberTable</span><span class="o">:</span>
      <span class="n">line</span> <span class="n">8</span><span class="o">:</span> <span class="n">0</span>
      <span class="n">line</span> <span class="n">9</span><span class="o">:</span> <span class="n">4</span>
      <span class="n">line</span> <span class="n">10</span><span class="o">:</span> <span class="n">9</span>
      <span class="n">line</span> <span class="n">11</span><span class="o">:</span> <span class="n">14</span>
      <span class="n">line</span> <span class="n">12</span><span class="o">:</span> <span class="n">19</span>
    <span class="n">LocalVariableTable</span><span class="o">:</span>
      <span class="n">Start</span>  <span class="n">Length</span>  <span class="n">Slot</span>  <span class="n">Name</span>   <span class="n">Signature</span>
          <span class="n">0</span>      <span class="n">20</span>     <span class="n">0</span>  <span class="k">this</span>   <span class="n">Lcom</span><span class="o">/</span><span class="n">test</span><span class="o">/</span><span class="n">Score</span><span class="o">;</span>
          <span class="n">0</span>      <span class="n">20</span>     <span class="n">1</span>  <span class="n">name</span>   <span class="n">Ljava</span><span class="o">/</span><span class="n">lang</span><span class="o">/</span><span class="n">String</span><span class="o">;</span>
          <span class="n">0</span>      <span class="n">20</span>     <span class="n">2</span>    <span class="n">id</span>   <span class="n">Ljava</span><span class="o">/</span><span class="n">lang</span><span class="o">/</span><span class="n">String</span><span class="o">;</span>
          <span class="n">0</span>      <span class="n">20</span>     <span class="n">3</span> <span class="n">score</span>   <span class="n">Ljava</span><span class="o">/</span><span class="n">lang</span><span class="o">/</span><span class="n">Number</span><span class="o">;</span>   <span class="c1">//可以看到score的类型直接被编译为Number类
</span><span class="c1"></span>
  <span class="kd">public</span> <span class="n">T</span> <span class="nf">getScore</span><span class="o">();</span>
    <span class="n">LineNumberTable</span><span class="o">:</span>
      <span class="n">line</span> <span class="n">15</span><span class="o">:</span> <span class="n">0</span>
    <span class="n">LocalVariableTable</span><span class="o">:</span>
      <span class="n">Start</span>  <span class="n">Length</span>  <span class="n">Slot</span>  <span class="n">Name</span>   <span class="n">Signature</span>
          <span class="n">0</span>       <span class="n">5</span>     <span class="n">0</span>  <span class="k">this</span>   <span class="n">Lcom</span><span class="o">/</span><span class="n">test</span><span class="o">/</span><span class="n">Score</span><span class="o">;</span>
<span class="o">}</span>

</code></pre></div><p>因此，一旦确立上限后，编译器会自动将类型提升到上限类型。</p>
<h3 id="钻石运算符">钻石运算符</h3>
<p>我们发现，每次创建泛型对象都需要在前后都标明类型，但是实际上后面的类型声明是可以去掉的，因为我们在传入参数时或定义泛型类的引用时，就已经明确了类型，因此JDK1.7提供了钻石运算符来简化代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Score</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="n">10</span><span class="o">);</span>  <span class="c1">//1.7之前
</span><span class="c1"></span>
<span class="n">Score</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">score</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Score</span><span class="o">&lt;&gt;(</span><span class="s">&#34;数据结构与算法基础&#34;</span><span class="o">,</span> <span class="s">&#34;EP074512&#34;</span><span class="o">,</span> <span class="n">10</span><span class="o">);</span>  <span class="c1">//1.7之后
</span></code></pre></div><h3 id="泛型与多态">泛型与多态</h3>
<p>泛型不仅仅可以可以定义在类上，同时也能定义在接口上：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">ScoreInterface</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="n">T</span> <span class="nf">getScore</span><span class="o">();</span>
    <span class="kt">void</span> <span class="nf">setScore</span><span class="o">(</span><span class="n">T</span> <span class="n">t</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>当实现此接口时，我们可以选择在实现类明确泛型类型或是继续使用此泛型，让具体创建的对象来确定类型。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Score</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="kd">implements</span> <span class="n">ScoreInterface</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;{</span>   <span class="c1">//将Score转变为泛型类&lt;T&gt;
</span><span class="c1"></span>    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">id</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">T</span> <span class="n">score</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">Score</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">id</span><span class="o">,</span> <span class="n">T</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span> 
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">id</span> <span class="o">=</span> <span class="n">id</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">T</span> <span class="nf">getScore</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setScore</span><span class="o">(</span><span class="n">T</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">StringScore</span> <span class="kd">implements</span> <span class="n">ScoreInterface</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;{</span>   <span class="c1">//在实现时明确类型
</span><span class="c1"></span>
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getScore</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setScore</span><span class="o">(</span><span class="n">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>

    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>抽象类同理，这里就不多做演示了。</p>
<h3 id="多态类型擦除">多态类型擦除</h3>
<p>思考一个问题，既然继承后明确了泛型类型，那么为什么<code>@Override</code>不会出现错误呢，重写的条件是需要和父类的返回值类型、形式参数一致，而泛型默认的原始类型是Object类型，子类明确后变为Number类型，这显然不满足重写的条件，但是为什么依然能编译通过呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">class</span> <span class="nc">A</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;{</span>
    <span class="kd">private</span> <span class="n">T</span> <span class="n">t</span><span class="o">;</span>
    <span class="kd">public</span> <span class="n">T</span> <span class="nf">get</span><span class="o">(){</span>
        <span class="k">return</span> <span class="n">t</span><span class="o">;</span>
    <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">set</span><span class="o">(</span><span class="n">T</span> <span class="n">t</span><span class="o">){</span>
        <span class="k">this</span><span class="o">.</span><span class="na">t</span><span class="o">=</span><span class="n">t</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">B</span> <span class="kd">extends</span> <span class="n">A</span><span class="o">&lt;</span><span class="n">Number</span><span class="o">&gt;{</span>
    <span class="kd">private</span> <span class="n">Number</span> <span class="n">n</span><span class="o">;</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">Number</span> <span class="nf">get</span><span class="o">(){</span>   <span class="c1">//这并不满足重写的要求，因为只能重写父类同样返回值和参数的方法，但是这样却能够通过编译！
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">t</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">set</span><span class="o">(</span><span class="n">Number</span> <span class="n">t</span><span class="o">){</span>
        <span class="k">this</span><span class="o">.</span><span class="na">t</span><span class="o">=</span><span class="n">t</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>通过反编译进行观察，实际上是编译器帮助我们生成了两个桥接方法用于支持重写：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="nd">@Override</span>
<span class="kd">public</span> <span class="n">Object</span> <span class="nf">get</span><span class="o">(){</span>
  <span class="k">return</span> <span class="k">this</span><span class="o">.</span><span class="na">get</span><span class="o">();</span><span class="c1">//调用返回Number的那个方法
</span><span class="c1"></span><span class="o">}</span>

<span class="nd">@Override</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">set</span><span class="o">(</span><span class="n">Object</span> <span class="n">t</span> <span class="o">){</span>
  <span class="k">this</span><span class="o">.</span><span class="na">set</span><span class="o">((</span><span class="n">Number</span><span class="o">)</span><span class="n">t</span> <span class="o">);</span> <span class="c1">//调用参数是Number的那个方法
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><hr>
<h2 id="数据结构基础">数据结构基础</h2>
<p>警告！本章最难的部分！</p>
<p>学习集合类之前，我们还有最关键的内容需要学习，同第一章一样，自底向上才是最佳的学习方向，比起直接带大家认识集合类，不如先了解一下数据结构，只有了解了数据结构基础，才能更好地学习集合类，同时，数据结构也是你以后深入学习JDK源码的必备条件！（学习不要快餐式！）当然，我们主要是讲解Java，数据结构作为铺垫作用，所以我们只会讲解关键的部分，其他部分可以下去自行了解。</p>
<p>在计算机科学中，数据结构是一种数据组织、管理和存储的格式,它可以帮助我们实现对数据高效的访问和修改。更准确地说,数据结构是数据值的集合，可以体现数据值之间的关系，以及可以对数据进行应用的函数或操作。</p>
<p>通俗地说，我们需要去学习在计算机中如何去更好地管理我们的数据，才能让我们对我们的数据控制更加灵活！</p>
<h3 id="线性表">线性表</h3>
<p>线性表是最基本的一种数据结构，它是表示一组相同类型数据的有限序列，你可以把它与数组进行参考，但是它并不是数组，线性表是一种表结构，它能够支持数据的插入、删除、更新、查询等，同时数组可以随意存放在数组中任意位置，而线性表只能依次有序排列，不能出现空隙，因此，我们需要进一步的设计。</p>
<h4 id="顺序表">顺序表</h4>
<p>将数据依次存储在连续的整块物理空间中，这种存储结构称为<code>顺序存储结构</code>，而以这种方式实现的线性表，我们称为<code>顺序表</code>。</p>
<p>同样的，表中的每一个个体都被称为<code>元素</code>，元素左边的元素（上一个元素），称为<code>前驱</code>，同理，右边的元素（后一个元素）称为<code>后驱</code>。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img1.baidu.com/it/u=4003060195,523881164&amp;fm=26&amp;fmt=auto"
        data-srcset="https://img1.baidu.com/it/u=4003060195%2c523881164&amp;fm=26&amp;fmt=auto, https://img1.baidu.com/it/u=4003060195%2c523881164&amp;fm=26&amp;fmt=auto 1.5x, https://img1.baidu.com/it/u=4003060195%2c523881164&amp;fm=26&amp;fmt=auto 2x"
        data-sizes="auto"
        alt="https://img1.baidu.com/it/u=4003060195,523881164&amp;fm=26&amp;fmt=auto"
        title="img" /></p>
<p>我们设计线性表的目标就是为了去更好地管理我们的数据，也就是说，我们可以基于数组，来进行封装，实现增删改查！既然要存储一组数据，那么很容易联想到我们之前学过的数组，数组就能够容纳一组同类型的数据。</p>
<p>目标：以数组为底层，编写以下抽象类的具体实现</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * 线性表抽象类
</span><span class="cm"> * @param &lt;E&gt; 存储的元素(Element)类型
</span><span class="cm"> */</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">AbstractList</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="cm">/**
</span><span class="cm">     * 获取表的长度
</span><span class="cm">     * @return 顺序表的长度
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">int</span> <span class="nf">size</span><span class="o">();</span>

    <span class="cm">/**
</span><span class="cm">     * 添加一个元素
</span><span class="cm">     * @param e 元素
</span><span class="cm">     * @param index 要添加的位置(索引)
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">void</span> <span class="nf">add</span><span class="o">(</span><span class="n">E</span> <span class="n">e</span><span class="o">,</span> <span class="kt">int</span> <span class="n">index</span><span class="o">);</span>

    <span class="cm">/**
</span><span class="cm">     * 移除指定位置的元素
</span><span class="cm">     * @param index 位置
</span><span class="cm">     * @return 移除的元素
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="n">E</span> <span class="nf">remove</span><span class="o">(</span><span class="kt">int</span> <span class="n">index</span><span class="o">);</span>

    <span class="cm">/**
</span><span class="cm">     * 获取指定位置的元素
</span><span class="cm">     * @param index 位置
</span><span class="cm">     * @return 元素
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="n">E</span> <span class="nf">get</span><span class="o">(</span><span class="kt">int</span> <span class="n">index</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><h4 id="链表">链表</h4>
<p>数据分散的存储在物理空间中，通过一根线保存着它们之间的逻辑关系，这种存储结构称为<code>链式存储结构</code></p>
<p>实际上，就是每一个结点存放一个元素和一个指向下一个结点的引用（C语言里面是指针，Java中就是对象的引用，代表下一个结点对象）</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img1.baidu.com/it/u=3381038214,3369355034&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        data-srcset="https://img1.baidu.com/it/u=3381038214%2c3369355034&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg, https://img1.baidu.com/it/u=3381038214%2c3369355034&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 1.5x, https://img1.baidu.com/it/u=3381038214%2c3369355034&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 2x"
        data-sizes="auto"
        alt="https://img1.baidu.com/it/u=3381038214,3369355034&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        title="img" /></p>
<p>利用这种思想，我们再来尝试实现上面的抽象类，从实际的代码中感受！</p>
<p>比较：顺序表和链表的优异？</p>
<p>顺序表优缺点：</p>
<ul>
<li>访问速度快，随机访问性能高</li>
<li>插入和删除的效率低下，极端情况下需要变更整个表</li>
<li>不易扩充，需要复制并重新创建数组</li>
</ul>
<p>链表优缺点：</p>
<ul>
<li>插入和删除效率高，只需要改变连接点的指向即可</li>
<li>动态扩充容量，无需担心容量问题</li>
<li>访问元素需要依次寻找，随机访问元素效率低下</li>
</ul>
<p>链表只能指向后面，能不能指向前面呢？双向链表！</p>
<hr>
<p>栈和队列实际上就是对线性表加以约束的一种数据结构，如果前面的线性表的掌握已经ok，那么栈和队列就非常轻松了！</p>
<h4 id="栈">栈</h4>
<p>栈遵循先入后出原则，只能在线性表的一端添加和删除元素。我们可以把栈看做一个杯子，杯子只有一个口进出，最低处的元素只能等到上面的元素离开杯子后，才能离开。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img2.baidu.com/it/u=4172728777,3669222584&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        data-srcset="https://img2.baidu.com/it/u=4172728777%2c3669222584&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg, https://img2.baidu.com/it/u=4172728777%2c3669222584&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 1.5x, https://img2.baidu.com/it/u=4172728777%2c3669222584&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 2x"
        data-sizes="auto"
        alt="https://img2.baidu.com/it/u=4172728777,3669222584&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        title="img" /></p>
<p>向栈中插入一个元素时，称为<code>入栈（压栈）</code>，移除栈顶元素称为<code>出栈</code>，我们需要尝试实现以下抽象类型：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * 抽象类型栈，待实现
</span><span class="cm"> * @param &lt;E&gt; 元素类型
</span><span class="cm"> */</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">AbstractStack</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="o">{</span>

    <span class="cm">/**
</span><span class="cm">     * 出栈操作
</span><span class="cm">     * @return 栈顶元素
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="n">E</span> <span class="nf">pop</span><span class="o">();</span>

    <span class="cm">/**
</span><span class="cm">     * 入栈操作
</span><span class="cm">     * @param e 元素
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">void</span> <span class="nf">push</span><span class="o">(</span><span class="n">E</span> <span class="n">e</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>其实，我们的JVM在处理方法调用时，也是一个栈操作：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img0.baidu.com/it/u=1098322354,1667908648&amp;fm=26&amp;fmt=auto"
        data-srcset="https://img0.baidu.com/it/u=1098322354%2c1667908648&amp;fm=26&amp;fmt=auto, https://img0.baidu.com/it/u=1098322354%2c1667908648&amp;fm=26&amp;fmt=auto 1.5x, https://img0.baidu.com/it/u=1098322354%2c1667908648&amp;fm=26&amp;fmt=auto 2x"
        data-sizes="auto"
        alt="https://img0.baidu.com/it/u=1098322354,1667908648&amp;fm=26&amp;fmt=auto"
        title="img" /></p>
<p>所以说，如果玩不好递归，就会像这样：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">go</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">go</span><span class="o">(){</span>
        <span class="n">go</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="n">Exception</span> <span class="n">in</span> <span class="n">thread</span> <span class="s">&#34;main&#34;</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">StackOverflowError</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
	<span class="n">at</span> <span class="n">com</span><span class="o">.</span><span class="na">test</span><span class="o">.</span><span class="na">Main</span><span class="o">.</span><span class="na">go</span><span class="o">(</span><span class="n">Main</span><span class="o">.</span><span class="na">java</span><span class="o">:</span><span class="n">13</span><span class="o">)</span>
  <span class="o">...</span>
</code></pre></div><p>栈的深度是有限制的，如果达到限制，将会出现<code>StackOverflowError</code>错误（注意是错误！说明是JVM出现了问题）</p>
<h4 id="队列">队列</h4>
<p>队列同样也是受限制的线性表，不过队列就像我们排队一样，只能从队尾开始排，从队首出。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img1.baidu.com/it/u=2682903513,371531599&amp;fm=26&amp;fmt=auto"
        data-srcset="https://img1.baidu.com/it/u=2682903513%2c371531599&amp;fm=26&amp;fmt=auto, https://img1.baidu.com/it/u=2682903513%2c371531599&amp;fm=26&amp;fmt=auto 1.5x, https://img1.baidu.com/it/u=2682903513%2c371531599&amp;fm=26&amp;fmt=auto 2x"
        data-sizes="auto"
        alt="https://img1.baidu.com/it/u=2682903513,371531599&amp;fm=26&amp;fmt=auto"
        title="img" /></p>
<p>所以我们要实现以下内容：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java">
<span class="cm">/**
</span><span class="cm"> *
</span><span class="cm"> * @param &lt;E&gt;
</span><span class="cm"> */</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">AbstractQueue</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="o">{</span>

    <span class="cm">/**
</span><span class="cm">     * 进队操作
</span><span class="cm">     * @param e 元素
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">void</span> <span class="nf">offer</span><span class="o">(</span><span class="n">E</span> <span class="n">e</span><span class="o">);</span>

    <span class="cm">/**
</span><span class="cm">     * 出队操作
</span><span class="cm">     * @return 元素
</span><span class="cm">     */</span>
    <span class="kd">public</span> <span class="kd">abstract</span> <span class="n">E</span> <span class="nf">poll</span><span class="o">();</span>
<span class="o">}</span>

</code></pre></div><hr>
<h3 id="二叉树">二叉树</h3>
<p>本版块主要学习的是二叉树，树也是一种数据结构，但是它使用起来更加的复杂。</p>
<h4 id="树">树</h4>
<p>我们前面已经学习过链表了，我们知道链表是单个结点之间相连，也就是一种一对一的关系，而树则是一个结点连接多个结点，也就是一对多的关系。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img2.baidu.com/it/u=1603039729,2366298993&amp;fm=26&amp;fmt=auto"
        data-srcset="https://img2.baidu.com/it/u=1603039729%2c2366298993&amp;fm=26&amp;fmt=auto, https://img2.baidu.com/it/u=1603039729%2c2366298993&amp;fm=26&amp;fmt=auto 1.5x, https://img2.baidu.com/it/u=1603039729%2c2366298993&amp;fm=26&amp;fmt=auto 2x"
        data-sizes="auto"
        alt="https://img2.baidu.com/it/u=1603039729,2366298993&amp;fm=26&amp;fmt=auto"
        title="img" /></p>
<p>一个结点可以有N个子结点，就像上图一样，看起来就像是一棵树。而位于最顶端的结点（没有父结点）我们称为<code>根结点</code>，而结点拥有的子节点数量称为<code>度</code>，每向下一级称为一个<code>层次</code>，树中出现的最大层次称为树的<code>深度(高度)</code>。</p>
<h4 id="二叉树-1">二叉树</h4>
<p>二叉树是一种特殊的树，每个结点最多有两颗子树，所以二叉树中不存在度大于2的结点，位于两边的子结点称为左右子树（注意，左右子树是明确区分的，是左就是左，是右就是右）</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img1.baidu.com/it/u=4097712510,2021128931&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        data-srcset="https://img1.baidu.com/it/u=4097712510%2c2021128931&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg, https://img1.baidu.com/it/u=4097712510%2c2021128931&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 1.5x, https://img1.baidu.com/it/u=4097712510%2c2021128931&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 2x"
        data-sizes="auto"
        alt="https://img1.baidu.com/it/u=4097712510,2021128931&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        title="img" /></p>
<p>数学性质：</p>
<ul>
<li>在二叉树的第i层上最多有2^(i-1) 个节点。</li>
<li>二叉树中如果深度为k，那么最多有2^k-1个节点。</li>
</ul>
<p>设计一个二叉树结点类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TreeNode</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="n">E</span> <span class="n">e</span><span class="o">;</span>   <span class="c1">//当前结点数据
</span><span class="c1"></span>    <span class="kd">public</span> <span class="n">TreeNode</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">left</span><span class="o">;</span>   <span class="c1">//左子树
</span><span class="c1"></span>    <span class="kd">public</span> <span class="n">TreeNode</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">right</span><span class="o">;</span>   <span class="c1">//右子树
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><h4 id="二叉树的遍历">二叉树的遍历</h4>
<p>顺序表的遍历其实就是依次有序去访问表中每一个元素，而像二叉树这样的复杂结构，我们有四种遍历方式，他们是：前序遍历、中序遍历、后序遍历以及层序遍历，本版块我们主要讨论前三种遍历方式：</p>
<ul>
<li><strong>前序遍历</strong>：从二叉树的根结点出发，到达结点时就直接输出结点数据，按照先向左在向右的方向访问。ABCDEF</li>
<li><strong>中序遍历</strong>：从二叉树的根结点出发，优先输出左子树的节点的数据，再输出当前节点本身，最后才是右子树。CBDAEF</li>
<li><strong>后序遍历</strong>：从二叉树的根结点出发，优先遍历其左子树，再遍历右子树，最后在输出当前节点本身。CDBFEA</li>
</ul>
<h4 id="满二叉树和完全二叉树">满二叉树和完全二叉树</h4>
<p>满二叉树和完全二叉树其实就是特殊情况下的二叉树，满二叉树左右的所有叶子节点都在同一层，也就是说，完全把每一个层级都给加满了结点。完全二叉树与满二叉树不同的地方在于，它的最下层叶子节点可以不满，但是最下层的叶子节点必须靠左排布。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.examw.com%2Fncre%2FFiles%2F2011-6%2F20%2F93236613.gif&amp;refer=http%3A%2F%2Fwww.examw.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634373420&amp;t=19f3ed8195b15d0b8f49201cc2803759"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.examw.com%2Fncre%2FFiles%2F2011-6%2F20%2F93236613.gif&amp;refer=http%3A%2F%2Fwww.examw.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634373420&amp;t=19f3ed8195b15d0b8f49201cc2803759, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.examw.com%2Fncre%2FFiles%2F2011-6%2F20%2F93236613.gif&amp;refer=http%3A%2F%2Fwww.examw.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634373420&amp;t=19f3ed8195b15d0b8f49201cc2803759 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.examw.com%2Fncre%2FFiles%2F2011-6%2F20%2F93236613.gif&amp;refer=http%3A%2F%2Fwww.examw.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634373420&amp;t=19f3ed8195b15d0b8f49201cc2803759 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.examw.com%2Fncre%2FFiles%2F2011-6%2F20%2F93236613.gif&amp;refer=http%3A%2F%2Fwww.examw.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634373420&amp;t=19f3ed8195b15d0b8f49201cc2803759"
        title="img" /></p>
<p>其实满二叉树和完全二叉树就是有一定规律的二叉树，很容易理解。</p>
<h3 id="快速查找">快速查找</h3>
<p>我们之前提到的这些数据结构，很好地帮我们管理了数据，但是，如果需要查找某一个元素是否存在于数据结构中，如何才能更加高效的去完成呢？</p>
<h4 id="哈希表">哈希表</h4>
<p>通过前面的学习，我们发现，顺序表虽然查询效率高，但是插入删除有严重表更新的问题，而链表虽然弥补了更新问题，但是查询效率实在是太低了，能否有一种折中方案？哈希表！</p>
<p>不知大家在之前的学习中是否发现，我们的Object类中，定义了一个叫做<code>hashcode()</code>的方法？而这个方法呢，就是为了更好地支持哈希表的实现。<code>hashcode()</code>默认得到的是对象的内存地址，也就是说，每个对象的hashCode都不一样。</p>
<p>哈希表，其实本质上就是一个存放链表的数组，那么它是如何去存储数据的呢？我们先来看看长啥样：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2127470%2F202012%2F2127470-20201222194727385-1606433879.jpg&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634376519&amp;t=8cc6fc7a35e695cc5ba12687974daa54"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2127470%2F202012%2F2127470-20201222194727385-1606433879.jpg&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634376519&amp;t=8cc6fc7a35e695cc5ba12687974daa54, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2127470%2F202012%2F2127470-20201222194727385-1606433879.jpg&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634376519&amp;t=8cc6fc7a35e695cc5ba12687974daa54 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2127470%2F202012%2F2127470-20201222194727385-1606433879.jpg&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634376519&amp;t=8cc6fc7a35e695cc5ba12687974daa54 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2020.cnblogs.com%2Fblog%2F2127470%2F202012%2F2127470-20201222194727385-1606433879.jpg&amp;refer=http%3A%2F%2Fimg2020.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634376519&amp;t=8cc6fc7a35e695cc5ba12687974daa54"
        title="img" /></p>
<p>数组中每一个元素都是一个头结点，用于保存数据，那我们怎么确定数据应该放在哪一个位置呢？通过hash算法，我们能够瞬间得到元素应该放置的位置。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">//假设hash表长度为16，hash算法为：
</span><span class="c1"></span><span class="kd">private</span> <span class="kt">int</span> <span class="nf">hash</span><span class="o">(</span><span class="kt">int</span> <span class="n">hashcode</span><span class="o">){</span>
  <span class="k">return</span> <span class="n">hashcode</span> <span class="o">%</span> <span class="n">16</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>设想这样一个问题，如果计算出来的hash值和之前已经存在的元素相同了呢？这种情况我们称为<code>hash碰撞</code>，这也是为什么要将每一个表元素设置为一个链表的头结点的原因，一旦发现重复，我们可以往后继续添加节点。</p>
<p>当然，以上的hash表结构只是一种设计方案，在面对大额数据时，是不够用的，在JDK1.8中，集合类使用的是数组+二叉树的形式解决的（这里的二叉树是经过加强的二叉树，不是前面讲得简单二叉树，我们下一节就会开始讲）</p>
<h4 id="二叉排序树">二叉排序树</h4>
<p>我们前面学习的二叉树效率是不够的，我们需要的是一种效率更高的二叉树，因此，基于二叉树的改进，提出了二叉查找树，可以看到结构像下面这样：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img0.baidu.com/it/u=3674232536,1832030468&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        data-srcset="https://img0.baidu.com/it/u=3674232536%2c1832030468&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg, https://img0.baidu.com/it/u=3674232536%2c1832030468&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 1.5x, https://img0.baidu.com/it/u=3674232536%2c1832030468&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg 2x"
        data-sizes="auto"
        alt="https://img0.baidu.com/it/u=3674232536,1832030468&amp;fm=26&amp;fmt=auto&amp;gp=0.jpg"
        title="img" /></p>
<p>不难发现，每个节点的左子树，一定小于当前节点的值，每个节点的右子树，一定大于当前节点的值，这样的二叉树称为<code>二叉排序树</code>。利用二分搜索的思想，我们就可以快速查找某个节点！</p>
<h4 id="平衡二叉树">平衡二叉树</h4>
<p>在了解了二叉查找树之后，我们发现，如果根节点为10，现在加入到结点的值从9开始，依次减小到1，那么这个表就会很奇怪，就像下面这样：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20191127151205330.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE5MTA1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634378465&amp;t=eb9bf93cfb9191362d1170b93b06d902"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20191127151205330.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE5MTA1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634378465&amp;t=eb9bf93cfb9191362d1170b93b06d902, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20191127151205330.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE5MTA1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634378465&amp;t=eb9bf93cfb9191362d1170b93b06d902 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20191127151205330.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE5MTA1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634378465&amp;t=eb9bf93cfb9191362d1170b93b06d902 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg-blog.csdnimg.cn%2F20191127151205330.png%3Fx-oss-process%3Dimage%2Fwatermark%2Ctype_ZmFuZ3poZW5naGVpdGk%2Cshadow_10%2Ctext_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDE5MTA1%2Csize_16%2Ccolor_FFFFFF%2Ct_70&amp;refer=http%3A%2F%2Fimg-blog.csdnimg.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634378465&amp;t=eb9bf93cfb9191362d1170b93b06d902"
        title="img" /></p>
<p>显然，当所有的结点都排列到一边，这种情况下，查找效率会直接退化为最原始的二叉树！因此我们需要维持二叉树的平衡，才能维持原有的查找效率。</p>
<p>现在我们对二叉排序树加以约束，要求每个结点的左右两个子树的高度差的绝对值不超过1，这样的二叉树称为<code>平衡二叉树</code>，同时要求每个结点的左右子树都是平衡二叉树，这样，就不会因为一边的疯狂增加导致失衡。我们来看看以下几种情况：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://pic002.cnblogs.com/images/2012/214741/2012072218213884.png"
        data-srcset="https://pic002.cnblogs.com/images/2012/214741/2012072218213884.png, https://pic002.cnblogs.com/images/2012/214741/2012072218213884.png 1.5x, https://pic002.cnblogs.com/images/2012/214741/2012072218213884.png 2x"
        data-sizes="auto"
        alt="https://pic002.cnblogs.com/images/2012/214741/2012072218213884.png"
        title="img" /></p>
<p>左左失衡</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://pic002.cnblogs.com/images/2012/214741/2012072218444051.png"
        data-srcset="https://pic002.cnblogs.com/images/2012/214741/2012072218444051.png, https://pic002.cnblogs.com/images/2012/214741/2012072218444051.png 1.5x, https://pic002.cnblogs.com/images/2012/214741/2012072218444051.png 2x"
        data-sizes="auto"
        alt="https://pic002.cnblogs.com/images/2012/214741/2012072218444051.png"
        title="img" /></p>
<p>右右失衡</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://pic002.cnblogs.com/images/2012/214741/2012072219144367.png"
        data-srcset="https://pic002.cnblogs.com/images/2012/214741/2012072219144367.png, https://pic002.cnblogs.com/images/2012/214741/2012072219144367.png 1.5x, https://pic002.cnblogs.com/images/2012/214741/2012072219144367.png 2x"
        data-sizes="auto"
        alt="https://pic002.cnblogs.com/images/2012/214741/2012072219144367.png"
        title="img" /></p>
<p>左右失衡</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://pic002.cnblogs.com/images/2012/214741/2012072219540371.png"
        data-srcset="https://pic002.cnblogs.com/images/2012/214741/2012072219540371.png, https://pic002.cnblogs.com/images/2012/214741/2012072219540371.png 1.5x, https://pic002.cnblogs.com/images/2012/214741/2012072219540371.png 2x"
        data-sizes="auto"
        alt="https://pic002.cnblogs.com/images/2012/214741/2012072219540371.png"
        title="img" /></p>
<p>右左失衡</p>
<p>通过以上四种情况的处理，最终得到维护平衡二叉树的算法。</p>
<h4 id="红黑树">红黑树</h4>
<p>红黑树也是二叉排序树的一种改进，同平衡二叉树一样，红黑树也是一种维护平衡的二叉排序树，但是没有平衡二叉树那样严格（平衡二叉树每次插入新结点时，可能会出现大量的旋转，而红黑树保证不超过三次），红黑树降低了对于旋转的要求，因此效率有一定的提升同时实现起来也更加简单。但是红黑树的效率却高于平衡二叉树，红黑树也是JDK1.8中使用的数据结构！</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2018.cnblogs.com%2Fblog%2F1301290%2F201904%2F1301290-20190418213139526-1239863354.jpg&amp;refer=http%3A%2F%2Fimg2018.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634381313&amp;t=d60b654d81ee3930b8518f194c976409"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2018.cnblogs.com%2Fblog%2F1301290%2F201904%2F1301290-20190418213139526-1239863354.jpg&amp;refer=http%3A%2F%2Fimg2018.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634381313&amp;t=d60b654d81ee3930b8518f194c976409, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2018.cnblogs.com%2Fblog%2F1301290%2F201904%2F1301290-20190418213139526-1239863354.jpg&amp;refer=http%3A%2F%2Fimg2018.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634381313&amp;t=d60b654d81ee3930b8518f194c976409 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2018.cnblogs.com%2Fblog%2F1301290%2F201904%2F1301290-20190418213139526-1239863354.jpg&amp;refer=http%3A%2F%2Fimg2018.cnblogs.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634381313&amp;t=d60b654d81ee3930b8518f194c976409 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2018.cnblogs.com%2Fblog%2F1301290%2F201904%2F1301290-20190418213139526-1239863354.jpg&amp;refer=http%3A%2F%2Fimg2018.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634381313&amp;t=d60b654d81ee3930b8518f194c976409"
        title="img" /></p>
<p>红黑树的特性:
（1）每个节点或者是黑色，或者是红色。
（2）根节点是黑色。
（3）每个叶子节点的两边也需要表示（虽然没有，但是null也需要表示出来）是黑色。
（4）如果一个节点是红色的，则它的子节点必须是黑色的。
（5）从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。</p>
<p>我们来看看一个节点，是如何插入到红黑树中的：</p>
<p>基本的 插入规则和平衡二叉树一样，但是在插入后：</p>
<ol>
<li>将新插入的节点标记为红色</li>
<li>如果 X 是根结点(root)，则标记为黑色</li>
<li>如果 X 的 parent 不是黑色，同时 X 也不是 root:</li>
</ol>
<ul>
<li>
<p>3.1 如果 X 的 uncle (叔叔) 是红色</p>
</li>
<li>
<ul>
<li>3.1.1 将 parent 和 uncle 标记为黑色</li>
<li>3.1.2 将 grand parent (祖父) 标记为红色</li>
<li>3.1.3 让 X 节点的颜色与 X 祖父的颜色相同，然后重复步骤 2、3</li>
</ul>
</li>
<li>
<p>3.2 如果 X 的 uncle (叔叔) 是黑色，我们要分四种情况处理</p>
</li>
<li>
<ul>
<li>3.2.1 左左 (P 是 G 的左孩子，并且 X 是 P 的左孩子)</li>
<li>3.2.2 左右 (P 是 G 的左孩子，并且 X 是 P 的右孩子)</li>
<li>3.2.3 右右 (P 是 G 的右孩子，并且 X 是 P 的右孩子)</li>
<li>3.2.4 右左 (P 是 G 的右孩子，并且 X 是 P 的左孩子)</li>
<li>其实这种情况下处理就和我们的平衡二叉树一样了</li>
</ul>
</li>
</ul>
<hr>
<h2 id="认识集合类">认识集合类</h2>
<p>集合表示一组对象，称为其元素。一些集合允许重复的元素，而另一些则不允许。一些集合是有序的，而其他则是无序的。</p>
<p>集合类其实就是为了更好地组织、管理和操作我们的数据而存在的，包括列表、集合、队列、映射等数据结构。从这一块开始，我们会从源码角度给大家讲解（数据结构很重要！），不仅仅是教会大家如何去使用。</p>
<p>集合类最顶层不是抽象类而是接口，因为接口代表的是某个功能，而抽象类是已经快要成形的类型，不同的集合类的底层实现是不相同的，同时一个集合类可能会同时具有两种及以上功能（既能做队列也能做列表），所以采用接口会更加合适，接口只需定义支持的功能即可。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.mianfeiwendang.com%2Fpic%2F29a5b61e9e5e19fe10103b4c%2F1-356-jpg_6_0_______-858-0-0-858.jpg&amp;refer=http%3A%2F%2Fwww.mianfeiwendang.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634434848&amp;t=e696ab71af584ef08a38fc328956586c"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.mianfeiwendang.com%2Fpic%2F29a5b61e9e5e19fe10103b4c%2F1-356-jpg_6_0_______-858-0-0-858.jpg&amp;refer=http%3A%2F%2Fwww.mianfeiwendang.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634434848&amp;t=e696ab71af584ef08a38fc328956586c, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.mianfeiwendang.com%2Fpic%2F29a5b61e9e5e19fe10103b4c%2F1-356-jpg_6_0_______-858-0-0-858.jpg&amp;refer=http%3A%2F%2Fwww.mianfeiwendang.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634434848&amp;t=e696ab71af584ef08a38fc328956586c 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.mianfeiwendang.com%2Fpic%2F29a5b61e9e5e19fe10103b4c%2F1-356-jpg_6_0_______-858-0-0-858.jpg&amp;refer=http%3A%2F%2Fwww.mianfeiwendang.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634434848&amp;t=e696ab71af584ef08a38fc328956586c 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.mianfeiwendang.com%2Fpic%2F29a5b61e9e5e19fe10103b4c%2F1-356-jpg_6_0_______-858-0-0-858.jpg&amp;refer=http%3A%2F%2Fwww.mianfeiwendang.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634434848&amp;t=e696ab71af584ef08a38fc328956586c"
        title="img" /></p>
<h3 id="数组与集合">数组与集合</h3>
<p>相同之处：</p>
<ol>
<li>它们都是容器，都能够容纳一组元素。</li>
</ol>
<p>不同之处：</p>
<ol>
<li>数组的大小是固定的，集合的大小是可变的。</li>
<li>数组可以存放基本数据类型，但集合只能存放对象。</li>
<li>数组存放的类型只能是一种，但集合可以有不同种类的元素。</li>
</ol>
<h3 id="集合根接口collection">集合根接口Collection</h3>
<p>本接口中定义了全部的集合基本操作，我们可以在源码中看看。</p>
<p>我们再来看看List和Set以及Queue接口。</p>
<h2 id="集合类的使用">集合类的使用</h2>
<h3 id="list列表">List列表</h3>
<p>首先介绍ArrayList，它的底层是用数组实现的，内部维护的是一个可改变大小的数组，也就是我们之前所说的线性表！跟我们之前自己写的ArrayList相比，它更加的规范，同时继承自List接口。</p>
<p>先看看ArrayList的源码！</p>
<h4 id="基本操作">基本操作</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>  <span class="c1">//默认长度的列表
</span><span class="c1"></span><span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">listInit</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;(</span><span class="n">100</span><span class="o">);</span>  <span class="c1">//初始长度为100的列表
</span></code></pre></div><p>向列表中添加元素：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>
<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;yyds&#34;</span><span class="o">);</span>
<span class="n">list</span><span class="o">.</span><span class="na">contains</span><span class="o">(</span><span class="s">&#34;yyds&#34;</span><span class="o">);</span> <span class="c1">//是否包含某个元素
</span><span class="c1"></span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
</code></pre></div><p>移除元素：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;yyds&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="n">0</span><span class="o">);</span>   <span class="c1">//按下标移除元素
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="s">&#34;yyds&#34;</span><span class="o">);</span>    <span class="c1">//移除指定元素
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>也支持批量操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">ArrayList</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">addAll</span><span class="o">(</span><span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;());</span>   <span class="c1">//在尾部批量添加元素
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">removeAll</span><span class="o">(</span><span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;());</span>   <span class="c1">//批量移除元素（只有给定集合中存在的元素才会被移除）
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">retainAll</span><span class="o">(</span><span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;());</span>   <span class="c1">//只保留某些元素
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>我们再来看LinkedList，其实本质就是一个链表！我们来看看源码。</p>
<p>其实与我们之前编写的LinkedList不同之处在于，它内部使用的是一个双向链表：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">private</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">Node</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="n">E</span> <span class="n">item</span><span class="o">;</span>
    <span class="n">Node</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">next</span><span class="o">;</span>
    <span class="n">Node</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">prev</span><span class="o">;</span>

    <span class="n">Node</span><span class="o">(</span><span class="n">Node</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">prev</span><span class="o">,</span> <span class="n">E</span> <span class="n">element</span><span class="o">,</span> <span class="n">Node</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="n">next</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">item</span> <span class="o">=</span> <span class="n">element</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">next</span> <span class="o">=</span> <span class="n">next</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">prev</span> <span class="o">=</span> <span class="n">prev</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>当然，我们发现它还实现了Queue接口，所以LinkedList也能被当做一个队列或是栈来使用。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">LinkedList</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">offer</span><span class="o">(</span><span class="s">&#34;A&#34;</span><span class="o">);</span>   <span class="c1">//入队
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">.</span><span class="na">poll</span><span class="o">());</span>  <span class="c1">//出队
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="s">&#34;B&#34;</span><span class="o">);</span>    <span class="c1">//进栈
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">push</span><span class="o">(</span><span class="s">&#34;C&#34;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">.</span><span class="na">pop</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">.</span><span class="na">pop</span><span class="o">());</span>    <span class="c1">//出栈
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">.</span><span class="na">pop</span><span class="o">());</span>
<span class="o">}</span>
</code></pre></div><h4 id="利用代码块来快速添加内容">利用代码块来快速添加内容</h4>
<p>前面我们学习了匿名内部类，我们就可以利用代码块，来快速生成一个自带元素的List</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;(){{</span>    <span class="c1">//初始化时添加
</span><span class="c1"></span>  <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;A&#34;</span><span class="o">);</span>
  <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;B&#34;</span><span class="o">);</span>
<span class="o">}};</span>
</code></pre></div><p>如果是需要快速生成一个只读的List，后面我们会讲解Arrays工具类。</p>
<h4 id="集合的排序">集合的排序</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;(){</span>   <span class="c1">//Java9才支持匿名内部类使用钻石运算符
</span><span class="c1"></span>    <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
        <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
        <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
        <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">8</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">};</span>
<span class="n">list</span><span class="o">.</span><span class="na">sort</span><span class="o">((</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">{</span>    <span class="c1">//排序已经由JDK实现，现在只需要填入自定义规则，完成Comparator接口实现
</span><span class="c1"></span>  <span class="k">return</span> <span class="n">a</span> <span class="o">-</span> <span class="n">b</span><span class="o">;</span>    <span class="c1">//返回值小于0，表示a应该在b前面，返回值大于0，表示b应该在a后面，等于0则不进行交换
</span><span class="c1"></span><span class="o">});</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
</code></pre></div><h3 id="迭代器">迭代器</h3>
<h4 id="集合的遍历">集合的遍历</h4>
<p>所有的集合类，都支持foreach循环！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;(){</span>   <span class="c1">//Java9才支持匿名内部类使用钻石运算符
</span><span class="c1"></span>        <span class="o">{</span>
            <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
            <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
            <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
            <span class="k">this</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">8</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">};</span>
    <span class="k">for</span> <span class="o">(</span><span class="n">Integer</span> <span class="n">integer</span> <span class="o">:</span> <span class="n">list</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">integer</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>当然，也可以使用JDK1.8新增的forEach方法，它接受一个Consumer接口实现：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">list</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
<span class="o">});</span>
</code></pre></div><p>从JDK1.8开始，lambda表达式开始逐渐成为主流，我们需要去适应函数式编程的这种语法，包括批量替换，也是用到了函数式接口来完成的。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">list</span><span class="o">.</span><span class="na">replaceAll</span><span class="o">((</span><span class="n">i</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">{</span>
  <span class="k">if</span><span class="o">(</span><span class="n">i</span> <span class="o">==</span> <span class="n">2</span><span class="o">)</span> <span class="k">return</span> <span class="n">3</span><span class="o">;</span>   <span class="c1">//将所有的2替换为3
</span><span class="c1"></span>  <span class="k">else</span> <span class="k">return</span> <span class="n">i</span><span class="o">;</span>   <span class="c1">//不是2就不变
</span><span class="c1"></span><span class="o">});</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
</code></pre></div><h4 id="iterable和iterator接口">Iterable和Iterator接口</h4>
<p>我们之前学习数据结构时，已经得知，不同的线性表实现，在获取元素时的效率也不同，因此我们需要一种更好地方式来统一不同数据结构的遍历。</p>
<p>由于ArrayList对于随机访问的速度更快，而LinkedList对于顺序访问的速度更快，因此在上述的传统for循环遍历操作中，ArrayList的效率更胜一筹，因此我们要使得LinkedList遍历效率提升，就需要采用顺序访问的方式进行遍历，如果没有迭代器帮助我们统一标准，那么我们在应对多种集合类型的时候，就需要对应编写不同的遍历算法，很显然这样会降低我们的开发效率，而迭代器的出现就帮助我们解决了这个问题。</p>
<p>我们先来看看迭代器里面方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">Iterator</span><span class="o">&lt;</span><span class="n">E</span><span class="o">&gt;</span> <span class="o">{</span>
  <span class="c1">//...
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>每个集合类都有自己的迭代器，通过<code>iterator()</code>方法来获取：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">Iterator</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">iterator</span> <span class="o">=</span> <span class="n">list</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span>   <span class="c1">//生成一个新的迭代器
</span><span class="c1"></span><span class="k">while</span> <span class="o">(</span><span class="n">iterator</span><span class="o">.</span><span class="na">hasNext</span><span class="o">()){</span>    <span class="c1">//判断是否还有下一个元素
</span><span class="c1"></span>  <span class="n">Integer</span> <span class="n">i</span> <span class="o">=</span> <span class="n">iterator</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>     <span class="c1">//获取下一个元素（获取一个少一个）
</span><span class="c1"></span>  <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>迭代器生成后，默认指向第一个元素，每次调用<code>next()</code>方法，都会将指针后移，当指针移动到最后一个元素之后，调用<code>hasNext()</code>将会返回<code>false</code>，迭代器是一次性的，用完即止，如果需要再次使用，需要调用<code>iterator()</code>方法。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">ListIterator</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">iterator</span> <span class="o">=</span> <span class="n">list</span><span class="o">.</span><span class="na">listIterator</span><span class="o">();</span>   <span class="c1">//List还有一个更好地迭代器实现ListIterator
</span></code></pre></div><p><code>ListIterator</code>是List中独有的迭代器，在原有迭代器基础上新增了一些额外的操作。</p>
<hr>
<h3 id="set集合">Set集合</h3>
<p>我们之前已经看过<code>Set</code>接口的定义了，我们发现接口中定义的方法都是Collection中直接继承的，因此，Set支持的功能其实也就和Collection中定义的差不多，只不过使用方法上稍有不同。</p>
<p>Set集合特点：</p>
<ul>
<li>不允许出现重复元素</li>
<li>不支持随机访问（不允许通过下标访问）</li>
</ul>
<p>首先认识一下HashSet，它的底层就是采用哈希表实现的（我们在这里先不去探讨实现原理，因为底层实质上维护的是一个HashMap，我们学习了Map之后再来讨论）</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">HashSet</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">set</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashSet</span><span class="o">&lt;&gt;();</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">120</span><span class="o">);</span>    <span class="c1">//支持插入元素，但是不支持指定位置插入
</span><span class="c1"></span>    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">13</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">11</span><span class="o">);</span>
    <span class="k">for</span> <span class="o">(</span><span class="n">Integer</span> <span class="n">integer</span> <span class="o">:</span> <span class="n">set</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">integer</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>运行上面代码发现，最后Set集合中存在的元素顺序，并不是我们的插入顺序，这是因为HashSet底层是采用<code>哈希表</code>来实现的，实际的存放顺序是由Hash算法决定的。</p>
<p>那么我们希望数据按照我们插入的顺序进行保存该怎么办呢？我们可以使用LinkedHashSet：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">LinkedHashSet</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">set</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedHashSet</span><span class="o">&lt;&gt;();</span>  <span class="c1">//会自动保存我们的插入顺序
</span><span class="c1"></span>    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">120</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">13</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">11</span><span class="o">);</span>
    <span class="k">for</span> <span class="o">(</span><span class="n">Integer</span> <span class="n">integer</span> <span class="o">:</span> <span class="n">set</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">integer</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>LinkedHashSet底层维护的不再是一个HashMap，而是LinkedHashMap，它能够在插入数据时利用链表自动维护顺序，因此这样就能够保证我们插入顺序和最后的迭代顺序一致了。</p>
<p>还有一种Set叫做TreeSet，它会在元素插入时进行排序：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">TreeSet</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">set</span> <span class="o">=</span> <span class="k">new</span> <span class="n">TreeSet</span><span class="o">&lt;&gt;();</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">set</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>可以看到最后得到的结果并不是我们插入顺序，而是按照数字的大小进行排列。当然，我们也可以自定义排序规则：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">TreeSet</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">set</span> <span class="o">=</span> <span class="k">new</span> <span class="n">TreeSet</span><span class="o">&lt;&gt;((</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">b</span> <span class="o">-</span> <span class="n">a</span><span class="o">);</span>   <span class="c1">//在创建对象时指定规则即可
</span><span class="c1"></span>    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
    <span class="n">set</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">set</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>现在的结果就是我们自定义的排序规则了。</p>
<p>虽然Set集合只是粗略的进行了讲解，但是学习Map之后，我们还会回来看我们Set的底层实现，所以说最重要的还是Map。本节只需要记住Set的性质、使用即可。</p>
<hr>
<h3 id="map映射">Map映射</h3>
<h4 id="什么是映射">什么是映射</h4>
<p>我们在高中阶段其实已经学习过映射了，映射指两个元素的之间相互“对应”的关系，也就是说，我们的元素之间是两两对应的，是以键值对的形式存在。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://bkimg.cdn.bcebos.com/pic/7aec54e736d12f2e89cbcbb64dc2d5628435681d?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg"
        data-srcset="https://bkimg.cdn.bcebos.com/pic/7aec54e736d12f2e89cbcbb64dc2d5628435681d?x-bce-process=image/resize%2cm_lfit%2cw_268%2climit_1/format%2cf_jpg, https://bkimg.cdn.bcebos.com/pic/7aec54e736d12f2e89cbcbb64dc2d5628435681d?x-bce-process=image/resize%2cm_lfit%2cw_268%2climit_1/format%2cf_jpg 1.5x, https://bkimg.cdn.bcebos.com/pic/7aec54e736d12f2e89cbcbb64dc2d5628435681d?x-bce-process=image/resize%2cm_lfit%2cw_268%2climit_1/format%2cf_jpg 2x"
        data-sizes="auto"
        alt="https://bkimg.cdn.bcebos.com/pic/7aec54e736d12f2e89cbcbb64dc2d5628435681d?x-bce-process=image/resize,m_lfit,w_268,limit_1/format,f_jpg"
        title="映射" /></p>
<h4 id="map接口">Map接口</h4>
<p>Map就是为了实现这种数据结构而存在的，我们通过保存键值对的形式来存储映射关系。</p>
<p>我们先来看看Map接口中定义了哪些操作。</p>
<h4 id="hashmap和linkedhashmap">HashMap和LinkedHashMap</h4>
<p>HashMap的实现过程，相比List，就非常地复杂了，它并不是简简单单的表结构，而是利用哈希表存放映射关系，我们来看看HashMap是如何实现的，首先回顾我们之前学习的哈希表，它长这样：</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://upload-images.jianshu.io/upload_images/16566539-672ab962ae6dc500.png?imageMogr2/auto-orient/strip%7cimageView2/2/w/508/format/webp"
        data-srcset="https://upload-images.jianshu.io/upload_images/16566539-672ab962ae6dc500.png?imageMogr2/auto-orient/strip%7cimageView2/2/w/508/format/webp, https://upload-images.jianshu.io/upload_images/16566539-672ab962ae6dc500.png?imageMogr2/auto-orient/strip%7cimageView2/2/w/508/format/webp 1.5x, https://upload-images.jianshu.io/upload_images/16566539-672ab962ae6dc500.png?imageMogr2/auto-orient/strip%7cimageView2/2/w/508/format/webp 2x"
        data-sizes="auto"
        alt="https://upload-images.jianshu.io/upload_images/16566539-672ab962ae6dc500.png?imageMogr2/auto-orient/strip|imageView2/2/w/508/format/webp"
        title="img" /></p>
<p>哈希表的本质其实就是一个用于存放后续节点的头结点的数组，数组里面的每一个元素都是一个头结点（也可以说就是一个链表），当要新插入一个数据时，会先计算该数据的哈希值，找到数组下标，然后创建一个新的节点，添加到对应的链表后面。</p>
<p>而HashMap就是采用的这种方式，我们可以看到源码中同样定义了这样的一个结构：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * The table, initialized on first use, and resized as
</span><span class="cm"> * necessary. When allocated, length is always a power of two.
</span><span class="cm"> * (We also tolerate length zero in some operations to allow
</span><span class="cm"> * bootstrapping mechanics that are currently not needed.)
</span><span class="cm"> */</span>
<span class="kd">transient</span> <span class="n">Node</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;[]</span> <span class="n">table</span><span class="o">;</span>
</code></pre></div><p>这个表会在第一次使用时初始化，同时在必要时进行扩容，并且它的大小永远是2的倍数！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * The default initial capacity - MUST be a power of two.
</span><span class="cm"> */</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">DEFAULT_INITIAL_CAPACITY</span> <span class="o">=</span> <span class="n">1</span> <span class="o">&lt;&lt;</span> <span class="n">4</span><span class="o">;</span> <span class="c1">// aka 16
</span></code></pre></div><p>我们可以看到默认的大小为2的4次方，每次都需要是2的倍数，也就是说，下一次增长之后，大小会变成2的5次方。</p>
<p>我们现在需要思考一个问题，当我们表中的数据不断增加之后，链表会变得越来越长，这样会严重导致查询速度变慢，首先想到办法就是，我们可以对数组的长度进行扩容，来存放更多的链表，那么什么情况下会进行扩容呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * The load factor for the hash table.
</span><span class="cm"> *
</span><span class="cm"> * @serial
</span><span class="cm"> */</span>
<span class="kd">final</span> <span class="kt">float</span> <span class="n">loadFactor</span><span class="o">;</span>
</code></pre></div><p>我们还发现HashMap源码中有这样一个变量，也就是<code>负载因子</code>，那么它是干嘛的呢？</p>
<p>负载因子其实就是用来衡量当前情况是否需要进行扩容的标准。我们可以看到默认的负载因子是<code>0.75</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * The load factor used when none specified in constructor.
</span><span class="cm"> */</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kt">float</span> <span class="n">DEFAULT_LOAD_FACTOR</span> <span class="o">=</span> <span class="n">0</span><span class="o">.</span><span class="na">75f</span><span class="o">;</span>
</code></pre></div><p>那么负载因子是怎么控制扩容的呢？<code>0.75</code>的意思是，在插入新的结点后，如果当前数组的占用率达到75%则进行扩容。在扩容时，会将所有的数据，重新计算哈希值，得到一个新的下标，组成新的哈希表。</p>
<p>但是这样依然有一个问题，链表过长的情况还是有可能发生，所以，为了从根源上解决这个问题，在JDK1.8时，引入了红黑树这个数据结构。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://i0.hdslb.com/bfs/album/5884577601a5ab1aabe10ee95696557b8d3b5338.jpg"
        data-srcset="https://i0.hdslb.com/bfs/album/5884577601a5ab1aabe10ee95696557b8d3b5338.jpg, https://i0.hdslb.com/bfs/album/5884577601a5ab1aabe10ee95696557b8d3b5338.jpg 1.5x, https://i0.hdslb.com/bfs/album/5884577601a5ab1aabe10ee95696557b8d3b5338.jpg 2x"
        data-sizes="auto"
        alt="https://i0.hdslb.com/bfs/album/5884577601a5ab1aabe10ee95696557b8d3b5338.jpg"
        title="https://i0.hdslb.com/bfs/album/5884577601a5ab1aabe10ee95696557b8d3b5338.jpg" /></p>
<p>当链表的长度达到8时，会自动将链表转换为红黑树，这样能使得原有的查询效率大幅度降低！当使用红黑树之后，我们就可以利用二分搜索的思想，快速地去寻找我们想要的结果，而不是像链表一样挨个去看。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
</span><span class="cm"> * extends Node) so can be used as extension of either regular or
</span><span class="cm"> * linked node.
</span><span class="cm"> */</span>
<span class="kd">static</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">TreeNode</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="kd">extends</span> <span class="n">LinkedHashMap</span><span class="o">.</span><span class="na">Entry</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="o">{</span>
</code></pre></div><p>除了Node以外，HashMap还有TreeNode，很明显这就是为了实现红黑树而设计的内部类。不过我们发现，TreeNode并不是直接继承Node，而是使用了LinkedHashMap中的Entry实现，它保存了前后节点的顺序（也就是我们的插入顺序）。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * HashMap.Node subclass for normal LinkedHashMap entries.
</span><span class="cm"> */</span>
<span class="kd">static</span> <span class="kd">class</span> <span class="nc">Entry</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="kd">extends</span> <span class="n">HashMap</span><span class="o">.</span><span class="na">Node</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="o">{</span>
    <span class="n">Entry</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="n">before</span><span class="o">,</span> <span class="n">after</span><span class="o">;</span>
    <span class="n">Entry</span><span class="o">(</span><span class="kt">int</span> <span class="n">hash</span><span class="o">,</span> <span class="n">K</span> <span class="n">key</span><span class="o">,</span> <span class="n">V</span> <span class="n">value</span><span class="o">,</span> <span class="n">Node</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="n">next</span><span class="o">)</span> <span class="o">{</span>
        <span class="kd">super</span><span class="o">(</span><span class="n">hash</span><span class="o">,</span> <span class="n">key</span><span class="o">,</span> <span class="n">value</span><span class="o">,</span> <span class="n">next</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>LinkedHashMap是直接继承自HashMap，具有HashMap的全部性质，同时得益于每一个节点都是一个双向链表，保存了插入顺序，这样我们在遍历LinkedHashMap时，顺序就同我们的插入顺序一致。当然，也可以使用访问顺序，也就是说对于刚访问过的元素，会被排到最后一位。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">LinkedHashMap</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedHashMap</span><span class="o">&lt;&gt;(</span><span class="n">16</span><span class="o">,</span> <span class="n">0</span><span class="o">.</span><span class="na">75f</span><span class="o">,</span> <span class="kc">true</span><span class="o">);</span>  <span class="c1">//以访问顺序
</span><span class="c1"></span>    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">3</span><span class="o">,</span> <span class="s">&#34;C&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>观察结果，我们发现，刚访问的结果被排到了最后一位。</p>
<h4 id="treemap">TreeMap</h4>
<p>TreeMap其实就是自动维护顺序的一种Map，就和我们前面提到的TreeSet一样：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * The comparator used to maintain order in this tree map, or
</span><span class="cm"> * null if it uses the natural ordering of its keys.
</span><span class="cm"> *
</span><span class="cm"> * @serial
</span><span class="cm"> */</span>
<span class="kd">private</span> <span class="kd">final</span> <span class="n">Comparator</span><span class="o">&lt;?</span> <span class="kd">super</span> <span class="n">K</span><span class="o">&gt;</span> <span class="n">comparator</span><span class="o">;</span>

<span class="kd">private</span> <span class="kd">transient</span> <span class="n">Entry</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="n">root</span><span class="o">;</span>

<span class="cm">/**
</span><span class="cm">* Node in the Tree.  Doubles as a means to pass key-value pairs back to
</span><span class="cm">* user (see Map.Entry).
</span><span class="cm">*/</span>

<span class="kd">static</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">Entry</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="kd">implements</span> <span class="n">Map</span><span class="o">.</span><span class="na">Entry</span><span class="o">&lt;</span><span class="n">K</span><span class="o">,</span><span class="n">V</span><span class="o">&gt;</span> <span class="o">{</span>
</code></pre></div><p>我们发现它的内部直接维护了一个红黑树，就像它的名字一样，就是一个Tree，因为它默认就是有序的，所以说直接采用红黑树会更好。我们在创建时，直接给予一个比较规则即可。</p>
<h4 id="map的使用">Map的使用</h4>
<p>我们首先来看看Map的一些基本操作：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">3</span><span class="o">,</span> <span class="s">&#34;C&#34;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">1</span><span class="o">));</span>    <span class="c1">//获取Key为1的值
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">getOrDefault</span><span class="o">(</span><span class="n">0</span><span class="o">,</span> <span class="s">&#34;K&#34;</span><span class="o">));</span>  <span class="c1">//不存在就返回K
</span><span class="c1"></span>   	<span class="n">map</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>   <span class="c1">//移除这个Key的键值对
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>由于Map并未实现迭代器接口，因此不支持foreach，但是JDK1.8为我们提供了forEach方法使用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">3</span><span class="o">,</span> <span class="s">&#34;C&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">forEach</span><span class="o">((</span><span class="n">k</span><span class="o">,</span> <span class="n">v</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">k</span><span class="o">+</span><span class="s">&#34;-&gt;&#34;</span><span class="o">+</span><span class="n">v</span><span class="o">));</span>
  
  	<span class="k">for</span> <span class="o">(</span><span class="n">Map</span><span class="o">.</span><span class="na">Entry</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">entry</span> <span class="o">:</span> <span class="n">map</span><span class="o">.</span><span class="na">entrySet</span><span class="o">())</span> <span class="o">{</span>   <span class="c1">//也可以获取所有的Entry来foreach
</span><span class="c1"></span>      <span class="kt">int</span> <span class="n">key</span> <span class="o">=</span> <span class="n">entry</span><span class="o">.</span><span class="na">getKey</span><span class="o">();</span>
      <span class="n">String</span> <span class="n">value</span> <span class="o">=</span> <span class="n">entry</span><span class="o">.</span><span class="na">getValue</span><span class="o">();</span>
      <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">key</span><span class="o">+</span><span class="s">&#34; -&gt; &#34;</span><span class="o">+</span><span class="n">value</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>我们也可以单独获取所有的值或者是键：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">3</span><span class="o">,</span> <span class="s">&#34;C&#34;</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">keySet</span><span class="o">());</span>   <span class="c1">//直接获取所有的key
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">values</span><span class="o">());</span>   <span class="c1">//直接获取所有的值
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><h4 id="再谈set原理">再谈Set原理</h4>
<p>通过观察HashSet的源码发现，HashSet几乎都在操作内部维护的一个HashMap，也就是说，HashSet只是一个表壳，而内部维护的HashMap才是灵魂！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="c1">// Dummy value to associate with an Object in the backing Map
</span><span class="c1"></span><span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="n">Object</span> <span class="n">PRESENT</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Object</span><span class="o">();</span>
</code></pre></div><p>我们发现，在添加元素时，其实添加的是一个键为我们插入的元素，而值就是<code>PRESENT</code>常量：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * Adds the specified element to this set if it is not already present.
</span><span class="cm"> * More formally, adds the specified element &lt;tt&gt;e&lt;/tt&gt; to this set if
</span><span class="cm"> * this set contains no element &lt;tt&gt;e2&lt;/tt&gt; such that
</span><span class="cm"> * &lt;tt&gt;(e==null&amp;nbsp;?&amp;nbsp;e2==null&amp;nbsp;:&amp;nbsp;e.equals(e2))&lt;/tt&gt;.
</span><span class="cm"> * If this set already contains the element, the call leaves the set
</span><span class="cm"> * unchanged and returns &lt;tt&gt;false&lt;/tt&gt;.
</span><span class="cm"> *
</span><span class="cm"> * @param e element to be added to this set
</span><span class="cm"> * @return &lt;tt&gt;true&lt;/tt&gt; if this set did not already contain the specified
</span><span class="cm"> * element
</span><span class="cm"> */</span>
<span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">add</span><span class="o">(</span><span class="n">E</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">return</span> <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">e</span><span class="o">,</span> <span class="n">PRESENT</span><span class="o">)==</span><span class="kc">null</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div><p>观察其他的方法，也几乎都是在用HashMap做事，所以说，HashSet利用了HashMap内部的数据结构，轻松地就实现了Set定义的全部功能！</p>
<p>再来看TreeSet，实际上用的就是我们的TreeMap：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * The backing map.
</span><span class="cm"> */</span>
<span class="kd">private</span> <span class="kd">transient</span> <span class="n">NavigableMap</span><span class="o">&lt;</span><span class="n">E</span><span class="o">,</span><span class="n">Object</span><span class="o">&gt;</span> <span class="n">m</span><span class="o">;</span>
</code></pre></div><p>同理，这里就不多做阐述了。</p>
<h4 id="jdk18新增方法使用">JDK1.8新增方法使用</h4>
<p>最后，我们再来看看JDK1.8中集合类新增的一些操作（之前没有提及的）首先来看看<code>compute</code>方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">compute</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="o">(</span><span class="n">k</span><span class="o">,</span> <span class="n">v</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">{</span>   <span class="c1">//compute会将指定Key的值进行重新计算，若Key不存在，v会返回null
</span><span class="c1"></span>        <span class="k">return</span> <span class="n">v</span><span class="o">+</span><span class="s">&#34;M&#34;</span><span class="o">;</span>     <span class="c1">//这里返回原来的value+M
</span><span class="c1"></span>    <span class="o">});</span>
  	<span class="n">map</span><span class="o">.</span><span class="na">computeIfPresent</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="o">(</span><span class="n">k</span><span class="o">,</span> <span class="n">v</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">{</span>   <span class="c1">//当Key存在时存在则计算并赋予新的值
</span><span class="c1"></span>      <span class="k">return</span> <span class="n">v</span><span class="o">+</span><span class="s">&#34;M&#34;</span><span class="o">;</span>     <span class="c1">//这里返回原来的value+M
</span><span class="c1"></span>    <span class="o">});</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>也可以使用<code>computeIfAbsent</code>，当不存在Key时，计算并将键值对放入Map</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">1</span><span class="o">,</span> <span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">map</span><span class="o">.</span><span class="na">computeIfAbsent</span><span class="o">(</span><span class="n">0</span><span class="o">,</span> <span class="o">(</span><span class="n">k</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="o">{</span>   <span class="c1">//若不存在则计算并插入新的值
</span><span class="c1"></span>        <span class="k">return</span> <span class="s">&#34;M&#34;</span><span class="o">;</span>     <span class="c1">//这里返回M
</span><span class="c1"></span>    <span class="o">});</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>merge方法用于处理数据：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Student</span><span class="o">&gt;</span> <span class="n">students</span> <span class="o">=</span> <span class="n">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;yoni&#34;</span><span class="o">,</span> <span class="s">&#34;English&#34;</span><span class="o">,</span> <span class="n">80</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;yoni&#34;</span><span class="o">,</span> <span class="s">&#34;Chiness&#34;</span><span class="o">,</span> <span class="n">98</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;yoni&#34;</span><span class="o">,</span> <span class="s">&#34;Math&#34;</span><span class="o">,</span> <span class="n">95</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;taohai.wang&#34;</span><span class="o">,</span> <span class="s">&#34;English&#34;</span><span class="o">,</span> <span class="n">50</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;taohai.wang&#34;</span><span class="o">,</span> <span class="s">&#34;Chiness&#34;</span><span class="o">,</span> <span class="n">72</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;taohai.wang&#34;</span><span class="o">,</span> <span class="s">&#34;Math&#34;</span><span class="o">,</span> <span class="n">41</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;Seely&#34;</span><span class="o">,</span> <span class="s">&#34;English&#34;</span><span class="o">,</span> <span class="n">88</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;Seely&#34;</span><span class="o">,</span> <span class="s">&#34;Chiness&#34;</span><span class="o">,</span> <span class="n">89</span><span class="o">),</span>
            <span class="k">new</span> <span class="n">Student</span><span class="o">(</span><span class="s">&#34;Seely&#34;</span><span class="o">,</span> <span class="s">&#34;Math&#34;</span><span class="o">,</span> <span class="n">92</span><span class="o">)</span>
    <span class="o">);</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Integer</span><span class="o">&gt;</span> <span class="n">scoreMap</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
    <span class="n">students</span><span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">student</span> <span class="o">-&gt;</span> <span class="n">scoreMap</span><span class="o">.</span><span class="na">merge</span><span class="o">(</span><span class="n">student</span><span class="o">.</span><span class="na">getName</span><span class="o">(),</span> <span class="n">student</span><span class="o">.</span><span class="na">getScore</span><span class="o">(),</span> <span class="n">Integer</span><span class="o">::</span><span class="n">sum</span><span class="o">));</span>
    <span class="n">scoreMap</span><span class="o">.</span><span class="na">forEach</span><span class="o">((</span><span class="n">k</span><span class="o">,</span> <span class="n">v</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;key:&#34;</span> <span class="o">+</span> <span class="n">k</span> <span class="o">+</span> <span class="s">&#34;总分&#34;</span> <span class="o">+</span> <span class="s">&#34;value:&#34;</span> <span class="o">+</span> <span class="n">v</span><span class="o">));</span>
<span class="o">}</span>

<span class="kd">static</span> <span class="kd">class</span> <span class="nc">Student</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kd">final</span> <span class="n">String</span> <span class="n">type</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">score</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">Student</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">,</span> <span class="n">String</span> <span class="n">type</span><span class="o">,</span> <span class="kt">int</span> <span class="n">score</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">type</span> <span class="o">=</span> <span class="n">type</span><span class="o">;</span>
        <span class="k">this</span><span class="o">.</span><span class="na">score</span> <span class="o">=</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getName</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">name</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kt">int</span> <span class="nf">getScore</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">score</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getType</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">type</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><hr>
<h3 id="集合的嵌套">集合的嵌套</h3>
<p>既然集合类型中的元素类型是泛型，那么能否嵌套存储呢？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>   <span class="c1">//每一个映射都是 字符串&lt;-&gt;列表
</span><span class="c1"></span>    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;卡布奇诺今犹在&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;&gt;());</span>
    <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&#34;不见当年倒茶人&#34;</span><span class="o">,</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;&gt;());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">keySet</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">values</span><span class="o">());</span>
<span class="o">}</span>
</code></pre></div><p>通过Key获取到对应的值后，就是一个列表：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;卡布奇诺今犹在&#34;</span><span class="o">).</span><span class="na">add</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;卡布奇诺今犹在&#34;</span><span class="o">).</span><span class="na">get</span><span class="o">(</span><span class="n">0</span><span class="o">));</span>
</code></pre></div><p>让套娃继续下去：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;&gt;&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
<span class="o">}</span>
</code></pre></div><p>你也可以使用List来套娃别的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Set</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;&gt;&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">LinkedList</span><span class="o">&lt;&gt;();</span>
<span class="o">}</span>
</code></pre></div><h3 id="流stream和optional的使用">流Stream和Optional的使用</h3>
<p>Java 8 API添加了一个新的抽象称为流Stream，可以让你以一种声明的方式处理数据。Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。Stream API可以极大提高Java程序员的生产力，让程序员写出高效率、干净、简洁的代码。这种风格将要处理的元素集合看作一种流， 流在管道中传输， 并且可以在管道的节点上进行处理， 比如筛选， 排序，聚合等。元素流在管道中经过中间操作（intermediate operation）的处理，最后由最终操作(terminal operation)得到前面处理的结果。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fseo-1255598498.file.myqcloud.com%2Ffull%2F723b4e9e03e9f1cbd9078f60b265e3ddc8a582aa.jpg&amp;refer=http%3A%2F%2Fseo-1255598498.file.myqcloud.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634782830&amp;t=8d9a60d60087bec5ce0d09b763eb3805"
        data-srcset="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fseo-1255598498.file.myqcloud.com%2Ffull%2F723b4e9e03e9f1cbd9078f60b265e3ddc8a582aa.jpg&amp;refer=http%3A%2F%2Fseo-1255598498.file.myqcloud.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634782830&amp;t=8d9a60d60087bec5ce0d09b763eb3805, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fseo-1255598498.file.myqcloud.com%2Ffull%2F723b4e9e03e9f1cbd9078f60b265e3ddc8a582aa.jpg&amp;refer=http%3A%2F%2Fseo-1255598498.file.myqcloud.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634782830&amp;t=8d9a60d60087bec5ce0d09b763eb3805 1.5x, https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fseo-1255598498.file.myqcloud.com%2Ffull%2F723b4e9e03e9f1cbd9078f60b265e3ddc8a582aa.jpg&amp;refer=http%3A%2F%2Fseo-1255598498.file.myqcloud.com&amp;app=2002&amp;size=f9999%2c10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634782830&amp;t=8d9a60d60087bec5ce0d09b763eb3805 2x"
        data-sizes="auto"
        alt="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fseo-1255598498.file.myqcloud.com%2Ffull%2F723b4e9e03e9f1cbd9078f60b265e3ddc8a582aa.jpg&amp;refer=http%3A%2F%2Fseo-1255598498.file.myqcloud.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=jpeg?sec=1634782830&amp;t=8d9a60d60087bec5ce0d09b763eb3805"
        title="img" /></p>
<p>它看起来就像一个工厂的流水线一样！我们就可以把一个Stream当做流水线处理：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;A&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;B&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;C&#34;</span><span class="o">);</span>
  
  	<span class="c1">//移除为B的元素
</span><span class="c1"></span>  	<span class="n">Iterator</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">iterator</span> <span class="o">=</span> <span class="n">list</span><span class="o">.</span><span class="na">iterator</span><span class="o">();</span>
        <span class="k">while</span> <span class="o">(</span><span class="n">iterator</span><span class="o">.</span><span class="na">hasNext</span><span class="o">()){</span>
            <span class="k">if</span><span class="o">(</span><span class="n">iterator</span><span class="o">.</span><span class="na">next</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="s">&#34;B&#34;</span><span class="o">))</span> <span class="n">iterator</span><span class="o">.</span><span class="na">remove</span><span class="o">();</span>
        <span class="o">}</span>
  
  	<span class="c1">//Stream操作
</span><span class="c1"></span>    <span class="n">list</span> <span class="o">=</span> <span class="n">list</span>     <span class="c1">//链式调用
</span><span class="c1"></span>            <span class="o">.</span><span class="na">stream</span><span class="o">()</span>    <span class="c1">//获取流
</span><span class="c1"></span>            <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">e</span> <span class="o">-&gt;</span> <span class="o">!</span><span class="n">e</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="s">&#34;B&#34;</span><span class="o">))</span>   <span class="c1">//只允许所有不是B的元素通过流水线
</span><span class="c1"></span>            <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="n">Collectors</span><span class="o">.</span><span class="na">toList</span><span class="o">());</span>   <span class="c1">//将流水线中的元素重新收集起来，变回List
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>可能从上述例子中还不能感受到流处理带来的便捷，我们通过下面这个例子来感受一下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
  	<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>

    <span class="n">list</span> <span class="o">=</span> <span class="n">list</span>
            <span class="o">.</span><span class="na">stream</span><span class="o">()</span>
      			<span class="o">.</span><span class="na">distinct</span><span class="o">()</span>   <span class="c1">//去重（使用equals判断）
</span><span class="c1"></span>            <span class="o">.</span><span class="na">sorted</span><span class="o">((</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">b</span> <span class="o">-</span> <span class="n">a</span><span class="o">)</span>    <span class="c1">//进行倒序排列
</span><span class="c1"></span>            <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">e</span> <span class="o">-&gt;</span> <span class="n">e</span><span class="o">+</span><span class="n">1</span><span class="o">)</span>    <span class="c1">//每个元素都要执行+1操作
</span><span class="c1"></span>            <span class="o">.</span><span class="na">limit</span><span class="o">(</span><span class="n">2</span><span class="o">)</span>    <span class="c1">//只放行前两个元素
</span><span class="c1"></span>            <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="n">Collectors</span><span class="o">.</span><span class="na">toList</span><span class="o">());</span>

    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>当遇到大量的复杂操作时，我们就可以使用Stream来快速编写代码，这样不仅代码量大幅度减少，而且逻辑也更加清晰明了（如果你学习过SQL的话，你会发现它更像一个Sql语句）</p>
<p><strong>注意</strong>：不能认为每一步是直接依次执行的！</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
<span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>

<span class="n">list</span> <span class="o">=</span> <span class="n">list</span>
        <span class="o">.</span><span class="na">stream</span><span class="o">()</span>
        <span class="o">.</span><span class="na">distinct</span><span class="o">()</span>   <span class="c1">//断点
</span><span class="c1"></span>        <span class="o">.</span><span class="na">sorted</span><span class="o">((</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">b</span> <span class="o">-</span> <span class="n">a</span><span class="o">)</span>
        <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">e</span> <span class="o">-&gt;</span> <span class="o">{</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;&gt;&gt;&gt; &#34;</span><span class="o">+</span><span class="n">e</span><span class="o">);</span>   <span class="c1">//断点
</span><span class="c1"></span>            <span class="k">return</span> <span class="n">e</span><span class="o">+</span><span class="n">1</span><span class="o">;</span>
        <span class="o">})</span>
        <span class="o">.</span><span class="na">limit</span><span class="o">(</span><span class="n">2</span><span class="o">)</span>   <span class="c1">//断点
</span><span class="c1"></span>        <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="n">Collectors</span><span class="o">.</span><span class="na">toList</span><span class="o">());</span>
<span class="c1">//实际上，stream会先记录每一步操作，而不是直接开始执行内容，当整个链式调用完成后，才会依次进行！
</span></code></pre></div><p>接下来，我们用一堆随机数来进行更多流操作的演示：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Random</span> <span class="n">random</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Random</span><span class="o">();</span>  <span class="c1">//Random是一个随机数工具类
</span><span class="c1"></span>    <span class="n">random</span>
            <span class="o">.</span><span class="na">ints</span><span class="o">(-</span><span class="n">100</span><span class="o">,</span> <span class="n">100</span><span class="o">)</span>   <span class="c1">//生成-100~100之间的，随机int型数字（本质上是一个IntStream）
</span><span class="c1"></span>            <span class="o">.</span><span class="na">limit</span><span class="o">(</span><span class="n">10</span><span class="o">)</span>   <span class="c1">//只获取前10个数字（这是一个无限制的流，如果不加以限制，将会无限进行下去！）
</span><span class="c1"></span>            <span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">0</span><span class="o">)</span>   <span class="c1">//只保留小于0的数字
</span><span class="c1"></span>            <span class="o">.</span><span class="na">sorted</span><span class="o">()</span>    <span class="c1">//默认从小到大排序
</span><span class="c1"></span>            <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>   <span class="c1">//依次打印
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>我们可以生成一个统计实例来帮助我们快速进行统计：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Random</span> <span class="n">random</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Random</span><span class="o">();</span>  <span class="c1">//Random是一个随机数工具类
</span><span class="c1"></span>    <span class="n">IntSummaryStatistics</span> <span class="n">statistics</span> <span class="o">=</span> <span class="n">random</span>
            <span class="o">.</span><span class="na">ints</span><span class="o">(</span><span class="n">0</span><span class="o">,</span> <span class="n">100</span><span class="o">)</span>
            <span class="o">.</span><span class="na">limit</span><span class="o">(</span><span class="n">100</span><span class="o">)</span>
            <span class="o">.</span><span class="na">summaryStatistics</span><span class="o">();</span>    <span class="c1">//获取语法统计实例
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">statistics</span><span class="o">.</span><span class="na">getMax</span><span class="o">());</span>  <span class="c1">//快速获取最大值
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">statistics</span><span class="o">.</span><span class="na">getCount</span><span class="o">());</span>  <span class="c1">//获取数量
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">statistics</span><span class="o">.</span><span class="na">getAverage</span><span class="o">());</span>   <span class="c1">//获取平均值
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>普通的List只需要一个方法就可以直接转换到方便好用的IntStream了：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">4</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">stream</span><span class="o">()</span>
            <span class="o">.</span><span class="na">mapToInt</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="n">i</span><span class="o">)</span>    <span class="c1">//将每一个元素映射为Integer类型（这里因为本来就是Integer）
</span><span class="c1"></span>            <span class="o">.</span><span class="na">summaryStatistics</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div><p>我们还可以通过<code>flat</code>来对整个流进行进一步细分：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;A,B&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;C,D&#34;</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="s">&#34;E,F&#34;</span><span class="o">);</span>   <span class="c1">//我们想让每一个元素通过,进行分割，变成独立的6个元素
</span><span class="c1"></span>    <span class="n">list</span> <span class="o">=</span> <span class="n">list</span>
            <span class="o">.</span><span class="na">stream</span><span class="o">()</span>    <span class="c1">//生成流
</span><span class="c1"></span>            <span class="o">.</span><span class="na">flatMap</span><span class="o">(</span><span class="n">e</span> <span class="o">-&gt;</span> <span class="n">Arrays</span><span class="o">.</span><span class="na">stream</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">split</span><span class="o">(</span><span class="s">&#34;,&#34;</span><span class="o">)))</span>    <span class="c1">//分割字符串并生成新的流
</span><span class="c1"></span>            <span class="o">.</span><span class="na">collect</span><span class="o">(</span><span class="n">Collectors</span><span class="o">.</span><span class="na">toList</span><span class="o">());</span>   <span class="c1">//汇成新的List
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>   <span class="c1">//得到结果
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>我们也可以只通过Stream来完成所有数字的和，使用<code>reduce</code>方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
    <span class="kt">int</span> <span class="n">sum</span> <span class="o">=</span> <span class="n">list</span>
            <span class="o">.</span><span class="na">stream</span><span class="o">()</span>
            <span class="o">.</span><span class="na">reduce</span><span class="o">((</span><span class="n">a</span><span class="o">,</span> <span class="n">b</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="o">)</span>   <span class="c1">//计算规则为：a是上一次计算的值，b是当前要计算的参数，这里是求和
</span><span class="c1"></span>            <span class="o">.</span><span class="na">get</span><span class="o">();</span>    <span class="c1">//我们发现得到的是一个Optional类实例，不是我们返回的类型，通过get方法返回得到的值
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">sum</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>通过上面的例子，我们发现，Stream不喜欢直接给我们返回一个结果，而是通过Optinal的方式，那么什么是Optional呢？</p>
<p>Optional类是Java8为了解决null值判断问题，使用Optional类可以避免显式的null值判断（null的防御性检查），避免null导致的NPE（NullPointerException）。总而言之，就是对控制的一个判断，为了避免空指针异常。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">String</span> <span class="n">str</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
    <span class="k">if</span><span class="o">(</span><span class="n">str</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">){</span>   <span class="c1">//当str不为空时添加元素到List中
</span><span class="c1"></span>        <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">str</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><p>有了Optional之后，我们就可以这样写：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">String</span> <span class="n">str</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
    <span class="n">Optional</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">optional</span> <span class="o">=</span> <span class="n">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">str</span><span class="o">);</span>   <span class="c1">//转换为Optional
</span><span class="c1"></span>    <span class="n">optional</span><span class="o">.</span><span class="na">ifPresent</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>  <span class="c1">//当存在时再执行方法
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>就类似于Kotlin中的：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-js" data-lang="js"><span class="kd">var</span> <span class="nx">str</span> <span class="o">:</span> <span class="nb">String</span><span class="o">?</span> <span class="o">=</span> <span class="kc">null</span>
<span class="nx">str</span><span class="o">?</span><span class="p">.</span><span class="nx">upperCase</span><span class="p">()</span>
</code></pre></div><p>我们可以选择直接get或是当值为null时，获取备选值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">String</span> <span class="n">str</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
    <span class="n">Optional</span> <span class="n">optional</span> <span class="o">=</span> <span class="n">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">str</span><span class="o">);</span>   <span class="c1">//转换为Optional（可空）
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">optional</span><span class="o">.</span><span class="na">orElse</span><span class="o">(</span><span class="s">&#34;lbwnb&#34;</span><span class="o">));</span>
 		<span class="c1">// System.out.println(optional.get());   这样会直接报错
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>同样的，Optional也支持过滤操作和映射操作，不过是对于单对象而言：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">String</span> <span class="n">str</span> <span class="o">=</span> <span class="s">&#34;A&#34;</span><span class="o">;</span>
    <span class="n">Optional</span> <span class="n">optional</span> <span class="o">=</span> <span class="n">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">str</span><span class="o">);</span>   <span class="c1">//转换为Optional（可空）
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">optional</span><span class="o">.</span><span class="na">filter</span><span class="o">(</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">s</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="s">&#34;B&#34;</span><span class="o">)).</span><span class="na">get</span><span class="o">());</span>   <span class="c1">//被过滤了，此时元素为null，获取时报错
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">String</span> <span class="n">str</span> <span class="o">=</span> <span class="s">&#34;A&#34;</span><span class="o">;</span>
    <span class="n">Optional</span> <span class="n">optional</span> <span class="o">=</span> <span class="n">Optional</span><span class="o">.</span><span class="na">ofNullable</span><span class="o">(</span><span class="n">str</span><span class="o">);</span>   <span class="c1">//转换为Optional（可空）
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">optional</span><span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="n">s</span> <span class="o">+</span> <span class="s">&#34;A&#34;</span><span class="o">).</span><span class="na">get</span><span class="o">());</span>   <span class="c1">//在尾部追加一个A
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>其他操作自学了解。</p>
<h3 id="arrays和collections的使用">Arrays和Collections的使用</h3>
<p>Arrays是一个用于操作数组的工具类，它给我们提供了大量的工具方法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="cm">/**
</span><span class="cm"> * This class contains various methods for manipulating arrays (such as
</span><span class="cm"> * sorting and searching). This class also contains a static factory
</span><span class="cm"> * that allows arrays to be viewed as lists. &lt;- 注意，这句话很关键
</span><span class="cm"> *
</span><span class="cm"> * @author Josh Bloch
</span><span class="cm"> * @author Neal Gafter
</span><span class="cm"> * @author John Rose
</span><span class="cm"> * @since  1.2
</span><span class="cm"> */</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Arrays</span> <span class="o">{</span>
</code></pre></div><p>由于操作数组并不像集合那样方便，因此JDK提供了Arrays类来增强对数组操作，比如：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">int</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">6</span><span class="o">};</span>
    <span class="n">Arrays</span><span class="o">.</span><span class="na">sort</span><span class="o">(</span><span class="n">array</span><span class="o">);</span>   <span class="c1">//直接进行排序（底层原理：进行判断，元素少使用插入排序，大量元素使用双轴快速/归并排序）
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">array</span><span class="o">);</span>  <span class="c1">//由于int[]是一个对象类型，而数组默认是没有重写toString()方法，因此无法打印到想要的结果
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">array</span><span class="o">));</span>  <span class="c1">//我们可以使用Arrays.toString()来像集合一样直接打印每一个元素出来
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">int</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">6</span><span class="o">};</span>
    <span class="n">Arrays</span><span class="o">.</span><span class="na">sort</span><span class="o">(</span><span class="n">array</span><span class="o">);</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;排序后的结果：&#34;</span><span class="o">+</span><span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">array</span><span class="o">));</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;目标元素3位置为：&#34;</span><span class="o">+</span><span class="n">Arrays</span><span class="o">.</span><span class="na">binarySearch</span><span class="o">(</span><span class="n">array</span><span class="o">,</span> <span class="n">3</span><span class="o">));</span>  <span class="c1">//二分搜素，必须是已经排序好的数组！
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">int</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">6</span><span class="o">};</span>
    <span class="n">Arrays</span>
            <span class="o">.</span><span class="na">stream</span><span class="o">(</span><span class="n">array</span><span class="o">)</span>    <span class="c1">//将数组转换为流进行操作
</span><span class="c1"></span>            <span class="o">.</span><span class="na">sorted</span><span class="o">()</span>
            <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">int</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">6</span><span class="o">};</span>
    <span class="kt">int</span><span class="o">[]</span> <span class="n">array2</span> <span class="o">=</span> <span class="n">Arrays</span><span class="o">.</span><span class="na">copyOf</span><span class="o">(</span><span class="n">array</span><span class="o">,</span> <span class="n">array</span><span class="o">.</span><span class="na">length</span><span class="o">);</span>  <span class="c1">//复制一个一模一样的数组
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">array2</span><span class="o">));</span>

    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">array</span><span class="o">,</span> <span class="n">array2</span><span class="o">));</span>  <span class="c1">//比较两个数组是否值相同
</span><span class="c1"></span>
    <span class="n">Arrays</span><span class="o">.</span><span class="na">fill</span><span class="o">(</span><span class="n">array</span><span class="o">,</span> <span class="n">0</span><span class="o">);</span>   <span class="c1">//将数组的所有值全部填充为指定值
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">array</span><span class="o">));</span>

    <span class="n">Arrays</span><span class="o">.</span><span class="na">setAll</span><span class="o">(</span><span class="n">array2</span><span class="o">,</span> <span class="n">i</span> <span class="o">-&gt;</span> <span class="n">array2</span><span class="o">[</span><span class="n">i</span><span class="o">]</span> <span class="o">+</span> <span class="n">2</span><span class="o">);</span>  <span class="c1">//依次计算每一个元素（注意i是下标位置）
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">array2</span><span class="o">));</span>   <span class="c1">//这里计算让每个元素值+2
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>思考：当二维数组使用<code>Arrays.equals()</code>进行比较以及<code>Arrays.toString()</code>进行打印时，还会得到我们想要的结果吗？</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Integer</span><span class="o">[][]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">},</span> <span class="o">{</span><span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">},</span> <span class="o">{</span><span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">},</span> <span class="o">{</span><span class="n">6</span><span class="o">}};</span>
    <span class="n">Integer</span><span class="o">[][]</span> <span class="n">array2</span> <span class="o">=</span> <span class="o">{{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">},</span> <span class="o">{</span><span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">},</span> <span class="o">{</span><span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">},</span> <span class="o">{</span><span class="n">6</span><span class="o">}};</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">array</span><span class="o">));</span>    <span class="c1">//这样还会得到我们想要的结果吗？
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">array2</span><span class="o">,</span> <span class="n">array</span><span class="o">));</span>    <span class="c1">//这样还会得到true吗？
</span><span class="c1"></span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">deepToString</span><span class="o">(</span><span class="n">array</span><span class="o">));</span>   <span class="c1">//使用deepToString就能到打印多维数组
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">deepEquals</span><span class="o">(</span><span class="n">array2</span><span class="o">,</span> <span class="n">array</span><span class="o">));</span>   <span class="c1">//使用deepEquals就能比较多维数组
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>那么，一开始提到的当做List进行操作呢？我们可以使用<code>Arrays.asList()</code>来将数组转换为一个 <strong>固定长度的List</strong></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Integer</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">6</span><span class="o">};</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="n">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="n">array</span><span class="o">);</span>   <span class="c1">//不支持基本类型数组，必须是对象类型数组
</span><span class="c1"></span>    <span class="n">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="s">&#34;A&#34;</span><span class="o">,</span> <span class="s">&#34;B&#34;</span><span class="o">,</span> <span class="s">&#34;C&#34;</span><span class="o">);</span>  <span class="c1">//也可以逐个添加，因为是可变参数
</span><span class="c1"></span>
    <span class="n">list</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>    <span class="c1">//此List实现是长度固定的，是Arrays内部单独实现的一个类型，因此不支持添加操作
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="n">0</span><span class="o">);</span>   <span class="c1">//同理，也不支持移除
</span><span class="c1"></span>
    <span class="n">list</span><span class="o">.</span><span class="na">set</span><span class="o">(</span><span class="n">0</span><span class="o">,</span> <span class="n">8</span><span class="o">);</span>   <span class="c1">//直接设置指定下标的值就可以
</span><span class="c1"></span>    <span class="n">list</span><span class="o">.</span><span class="na">sort</span><span class="o">(</span><span class="n">Comparator</span><span class="o">.</span><span class="na">reverseOrder</span><span class="o">());</span>   <span class="c1">//也可以执行排序操作
</span><span class="c1"></span>    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>   <span class="c1">//也可以像List那样直接打印
</span><span class="c1"></span><span class="o">}</span>
</code></pre></div><p>文字游戏：<code>allows arrays to be viewed as lists</code>，实际上只是当做List使用，本质还是数组，因此数组的属性依然存在！因此如果要将数组快速转换为实际的List，可以像这样：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">Integer</span><span class="o">[]</span> <span class="n">array</span> <span class="o">=</span> <span class="o">{</span><span class="n">1</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">6</span><span class="o">};</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;(</span><span class="n">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="n">array</span><span class="o">));</span>
<span class="o">}</span>
</code></pre></div><p>通过自行创建一个真正的ArrayList并在构造时将Arrays的List值传递。</p>
<p>既然数组操作都这么方便了，集合操作能不能也安排点高级的玩法呢？那必须的，JDK为我们准备的Collocations类就是专用于集合的工具类：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">List</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">list</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="n">Collections</span><span class="o">.</span><span class="na">max</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
    <span class="n">Collections</span><span class="o">.</span><span class="na">min</span><span class="o">(</span><span class="n">list</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div><p>当然，Collections提供的内容相比Arrays会更多，希望大家下去自行了解，这里就不多做介绍了。</p>
<hr>
<h2 id="集合类编程实战">集合类编程实战</h2>
<h3 id="反转链表">反转链表</h3>
<p>1 &lt;- 3 &lt;- 5 &lt;- 7 &lt;- 9  转换为 1 &lt;- 3 &lt;- 5 &lt;- 7 &lt;- 9</p>
<p>现在有一个单链表，尝试将其所有节点倒序排列</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Main</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">Node</span> <span class="n">head</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Node</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">head</span><span class="o">.</span><span class="na">next</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Node</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
        <span class="n">head</span><span class="o">.</span><span class="na">next</span><span class="o">.</span><span class="na">next</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Node</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
        <span class="n">head</span><span class="o">.</span><span class="na">next</span><span class="o">.</span><span class="na">next</span><span class="o">.</span><span class="na">next</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Node</span><span class="o">(</span><span class="n">7</span><span class="o">);</span>
        <span class="n">head</span><span class="o">.</span><span class="na">next</span><span class="o">.</span><span class="na">next</span><span class="o">.</span><span class="na">next</span><span class="o">.</span><span class="na">next</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Node</span><span class="o">(</span><span class="n">9</span><span class="o">);</span>

        <span class="n">head</span> <span class="o">=</span> <span class="n">reverse</span><span class="o">(</span><span class="n">head</span><span class="o">);</span>

        <span class="k">while</span> <span class="o">(</span><span class="n">head</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">){</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">head</span><span class="o">.</span><span class="na">value</span><span class="o">+</span><span class="s">&#34; &#34;</span><span class="o">);</span>
            <span class="n">head</span> <span class="o">=</span> <span class="n">head</span><span class="o">.</span><span class="na">next</span><span class="o">;</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">Node</span> <span class="o">{</span>
        <span class="kd">public</span> <span class="kt">int</span> <span class="n">value</span><span class="o">;</span>
        <span class="kd">public</span> <span class="n">Node</span> <span class="n">next</span><span class="o">;</span>

        <span class="kd">public</span> <span class="nf">Node</span><span class="o">(</span><span class="kt">int</span> <span class="n">data</span><span class="o">)</span> <span class="o">{</span>
            <span class="k">this</span><span class="o">.</span><span class="na">value</span> <span class="o">=</span> <span class="n">data</span><span class="o">;</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="n">Node</span> <span class="nf">reverse</span><span class="o">(</span><span class="n">Node</span> <span class="n">head</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">//在这里实现
</span><span class="c1"></span>    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div><h3 id="重建二叉树">重建二叉树</h3>
<p>现在知道二叉树的前序: GDAFEMHZ，以及中序: ADEFGHMZ，请根据已知信息还原这颗二叉树。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://imgconvert.csdnimg.cn/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTcxMTEwMTExNTE3NDcx?x-oss-process=image/format,png"
        data-srcset="https://imgconvert.csdnimg.cn/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTcxMTEwMTExNTE3NDcx?x-oss-process=image/format%2cpng, https://imgconvert.csdnimg.cn/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTcxMTEwMTExNTE3NDcx?x-oss-process=image/format%2cpng 1.5x, https://imgconvert.csdnimg.cn/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTcxMTEwMTExNTE3NDcx?x-oss-process=image/format%2cpng 2x"
        data-sizes="auto"
        alt="https://imgconvert.csdnimg.cn/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTcxMTEwMTExNTE3NDcx?x-oss-process=image/format,png"
        title="这里写图片描述" /></p>
<h3 id="实现计算器">实现计算器</h3>
<p>实现一个计算器，要求输入一个计算公式（含加减乘除运算符，没有负数但是有小数），得到结果，比如输入：1+4*3/1.321，得到结果为：2.2</p>
<h3 id="字符串匹配kmp算法">字符串匹配（KMP算法）</h3>
<p>现在给定一个主字符串和一个子字符串，请判断主字符串是否包含子字符串，例如主字符串：ABCABCDHI，子字符串：ABCD，因此主字符串包含此子字符串；主字符串：ABCABCUISA，子字符串：ABCD，则不包含。</p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/">Java泛型与集合类</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-01-23</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类" data-hashtags="Java泛型与集合类"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-hashtag="Java泛型与集合类"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类" data-image="https://img-blog.csdnimg.cn/img_convert/7213ded01d686aab797968b2a6064358.png#pic_center"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类" data-description="Java泛型与集合类"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类" data-description="Java泛型与集合类"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/java%E6%B3%9B%E5%9E%8B%E4%B8%8E%E9%9B%86%E5%90%88%E7%B1%BB/" data-title="Java泛型与集合类"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/c&#43;&#43;%E7%9A%84%E6%A8%A1%E6%9D%BF%E5%86%99println/" class="prev" rel="prev" title="C&#43;&#43;变参模板运用实战——实现PrintLn"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/java%E5%BC%82%E5%B8%B8/" class="next" rel="next" title="Java异常处理机制">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
